35

My client pc is connected to as server pc via sockets over Ethernet, How do I find the IP of this client from the server side code.
The server is dishing out one socket per client in a new Thread.
When I do a csocket.getLocalAddress().toString() on the client socket I still get the Server IP address. (csocket is the socket that the Server has spawned upon a now client connection and passed it to a new Thread).

Kevin Boyd
  • 12,121
  • 28
  • 86
  • 128

4 Answers4

58

I believe you want to use the remote address instead:

csocket.getRemoteSocketAddress().toString();
Dev
  • 2,326
  • 24
  • 45
jheddings
  • 26,717
  • 8
  • 52
  • 65
  • How Get client ip from HttpServer object? see here: http://stackoverflow.com/questions/25274828/get-client-ip-from-httpserver –  Aug 12 '14 at 22:05
14

I think you might be looking for the getInetAddress method of the Socket object.

ameed
  • 1,132
  • 6
  • 25
Alex Shnayder
  • 1,362
  • 1
  • 13
  • 24
  • That gives the local address of the socket. The server needs to find the remote address from its perspective. – Stephen C Dec 03 '09 at 15:24
  • 12
    @Stephen: according to the Javadoc, `getInetAddress()` "returns the remote IP address to which this socket is connected, or null if the socket is not connected." – erickson Dec 03 '09 at 15:30
6

Use this code :

String ip=(((InetSocketAddress) socket.getRemoteSocketAddress()).getAddress()).toString().replace("/","");
Ahmad Aghazadeh
  • 16,571
  • 12
  • 101
  • 98
  • This is the correct answer. The other answers return "ipaddr:port". This answer returns the IP address and removes the port number. – John Hanley Sep 06 '19 at 10:16
4

Use getRemoteSocketAddress() instead.

erickson
  • 265,237
  • 58
  • 395
  • 493