Question

I wish I could create a small application that I print screen the IP address to which the socket is connected.

I'm trying this code:

 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();
        }
    }
}

But, I have never seen printed the IP address, If is necessary I can create a TextView and inside-It put the string ip. Where am I doing wrong? Thanks!

Was it helpful?

Solution

ulyssessPax:

When you connect/accept to/from a device via TCP sockets, you have the following method from that socket:

socket.getRemoteSocketAddress().toString() it gives you the remote IP address and the port number where it's connected. For example: 192.168.1.30:6000

socket.getLocalSocketAddress() it gives you the local IP address and the port number where it has established the connection. For example: 10.0.2.15:54471

Hope it's what you're looking for.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top