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?
We can use the getLocalHost() static method of the InetAddress class to obtain the localhost IP address.
TCP/IP Client Sockets. TCP/IP sockets are used to implement reliable two-way, persistent, point-to-point streaming connections between hosts on the Internet. The Java I/O system can use sockets to connect to other programs on the local system or on other systems on the Internet.
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.");
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With