How to turn Java class into one of its subclasses (SocketAddress and InetSocketAddress)

vasion picture vasion · Mar 20, 2010 · Viewed 7.3k times · Source

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?

Answer

Jared Russell picture Jared Russell · Mar 20, 2010

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.