Client socket - get IP java

I am implementing a TCP connection with sockets, and I need to get the IP address of the client socket on the server side. I used socketName.getRemoteSocketAddress()one that really returns an IP address, followed by the port id that I use! How can I get only the address, not the port?

+4
source share
2 answers

SocketAddressthat returns is actually a protocol dependent subclass . For internet protocols such as TCP in your case, you can pass it InetSocketAddress:

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

Then you can use the methods InetSocketAddressto get the necessary information, for example:

InetAddress inaddr = sockaddr.getAddress();

Inet4Address Inet6Address ( , instanceof, ), , IPv4:

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

:

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.");
}
+4
((InetSocketAddress)socketName).getAddress().toString()

- : /10.255.34.132, , , :

((InetSocketAddress)socketName).getAddress().toString().split("/")[1]
0

Source: https://habr.com/ru/post/1533749/


All Articles