Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Client socket - get IP - java

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?

like image 697
Rakim Avatar asked Mar 27 '14 14:03

Rakim


People also ask

How do I find my localhost IP address in Java?

We can use the getLocalHost() static method of the InetAddress class to obtain the localhost IP address.

What is TCP IP client socket in Java?

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.


1 Answers

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.");
}
like image 148
Jason C Avatar answered Oct 17 '22 05:10

Jason C