Client socket - get IP - java
Asked Answered
A

2

11

I am implementing a TCP connection with sockets and I need to get the IP of the client socket on the server side. I have used the socketName.getRemoteSocketAddress() which indeed returns the IP address followed by the port id I am using! how can I get just the address and not the port?

Abigael answered 27/3, 2014 at 14:38 Comment(0)
C
13

The SocketAddress that this returns is actually a protocol-dependent subclass. For internet protocols, such as TCP in your case, you can cast it to an InetSocketAddress:

InetSocketAddress sockaddr = (InetSocketAddress)socketName.getRemoteSocketAddress();

Then you can use the methods of InetSocketAddress to get the information you need, e.g.:

InetAddress inaddr = sockaddr.getAddress();

Then, you can cast that to an Inet4Address or Inet6Address depending on the address type (if you don't know, use instanceof to find out), e.g. if you know it is IPv4:

Inet4Address in4addr = (Inet4Address)inaddr;
byte[] ip4bytes = in4addr.getAddress(); // returns byte[4]
String ip4string = in4addr.toString();

Or, a more robust example:

SocketAddress socketAddress = socketName.getRemoteSocketAddress();

if (socketAddress instanceof InetSocketAddress) {
    InetAddress inetAddress = ((InetSocketAddress)socketAddress).getAddress();
    if (inetAddress instanceof Inet4Address)
        System.out.println("IPv4: " + inetAddress);
    else if (inetAddress instanceof Inet6Address)
        System.out.println("IPv6: " + inetAddress);
    else
        System.err.println("Not an IP address.");
} else {
    System.err.println("Not an internet protocol socket.");
}
Colvin answered 27/3, 2014 at 14:42 Comment(1)
worked perfectly just by using your first tip (before edit). Thank you!Abigael
T
3
((InetSocketAddress)socketName).getAddress().toString()

will return something like :/10.255.34.132 that contains the host name, you could try this if you don't want the host name:

((InetSocketAddress)socketName).getAddress().toString().split("/")[1]
Toilsome answered 17/5, 2017 at 12:16 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.