Client socket - get IP - java

核能气质少年 提交于 2019-12-30 08:32:10

问题


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?


回答1:


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



回答2:


((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]


来源:https://stackoverflow.com/questions/22690907/client-socket-get-ip-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!