Java: How can I get the connected port from an InetAddress?

DivideByHero picture DivideByHero · Aug 4, 2009 · Viewed 19.8k times · Source

I'm trying to build a Java NIO-based socket server using Apache Mina. I really need to know the port of the remote host, not just the IP address, and it seems that Mina only exposes a SocketAddress (which can be downcast to InetAddress) object. I can get the IP address from InetAddress, but I normally use Socket.getPort() to get the port number, but Mina appears to obscure these low-level objects. Is there another way? Thanks!

Answer

erickson picture erickson · Aug 4, 2009

Downcast the SocketAddress to InetSocketAddress (not InetAddress, which is not a sub-class); this exposes a port accessor.