سؤال

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?

هل كانت مفيدة؟

المحلول

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.");
}

نصائح أخرى

((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]
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top