Question

I'm beginner for programming in Android. I want use this method:

Socket socket;
socket.getInetAddress() ;

I would like print in a TextView the IP address to which I am connected. Is this possible? How should I do it?

Thanks!

I tried this, but nothing work

 public void onClick(View v) {

  Socket s = new Socket();
  String host ="10.10.20.xxxx";

try {
    s.connect( new InetSocketAddress( host, 6000 ), 1000 );

    InetAddress inetAddress = s.getLocalAddress();
    String ip = inetAddress.getHostAddress();
    //Now, I would like to have printed out the IP-address
    Toast.makeText(getBaseContext(), ip , Toast.LENGTH_SHORT).show();
//But nothing happens
} catch (IOException e) {
    e.printStackTrace();
    }
}
}
Was it helpful?

Solution

To obtain the address of the host that a socket is connected to, you should use getInetAddress() rather than getLocalAddress(). Thus, your code could look like this:

public void onClick(View v) {

    Socket s = new Socket();
    String host ="10.10.20.xxxx";

    try {
        s.connect( new InetSocketAddress( host, 6000 ), 1000 );

        InetAddress inetAddress = s.getInetAddress();        // <---- Here!
        String ip = inetAddress.getHostAddress();

        Toast.makeText(getBaseContext(), ip , Toast.LENGTH_SHORT).show();

    } catch (IOException e) {
        e.printStackTrace();
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top