4

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?

stivlo
  • 83,644
  • 31
  • 142
  • 199
vasion
  • 1,237
  • 3
  • 18
  • 29
  • welcome to SO. The answer that has been most useful and eventually solved your problem should be marked as accepted. This is done using the tick below the vote counter. – Bozho Mar 20 '10 at 17:43

3 Answers3

7

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
  • 10,804
  • 6
  • 30
  • 31
  • 1
    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 Mar 20 '10 at 17:41
4

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.

Community
  • 1
  • 1
Bozho
  • 588,226
  • 146
  • 1,060
  • 1,140
1

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

uthark
  • 5,333
  • 2
  • 43
  • 59