views:

154

answers:

3

I am trying to get the IP of a socket connection in string form.

I am using a framework, which returns the SocketAddress of the received message. How can i transform it to InetSocketAddress or InetAddress?

+1  A: 

Actually SocketAddress is an abstract class, so you receive some subclass of it. Did you try to cast returned SocketAddress to InetSocketAddress?

uthark
+3  A: 

If your certain that the object is an InetSocketAddress then simply cast it:

SocketAddress sockAddr = ...
InetSocketAddress inetAddr = (InetSocketAddress)sockAddr;

You can then call the getAddress() method on inetAddr to get the InetAddress object associated with it.

Jared Russell
Thanks, I am much more of a php dev and new to Java, so the whole casting process is new to me. Thanks a lot
vasion
+3  A: 

You can try casting to it. In this case this is downcasting.

InetSocketAddress isa = (InetSocketAddress) socketAddress;

However, this may throw ClassCastException if the class isn't really what you expect.

Checks can be made on this via the instanceof operator:

if (socketAddress instanceof InetSocketAddress) {
    InetSocketAddress isa = (InetSocketAddress) socketAddress;
    // invoke methods on "isa". This is now safe - no risk of exceptions
}

The same check can be done for other subclasses of SocketAddress.

Bozho