Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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!

like image 671
DivideByHero Avatar asked Aug 04 '09 20:08

DivideByHero


People also ask

What is InetSocketAddress Java?

public InetSocketAddress(int port) Creates a socket address where the IP address is the wildcard address and the port number a specified value. A valid port value is between 0 and 65535. A port number of zero will let the system pick up an ephemeral port in a bind operation.

What is InetAddress explain in detail?

InetAddress class provides methods to get the IP address of any hostname. An IP address is represented by 32-bit or 128-bit unsigned number. InetAddress can handle both IPv4 and IPv6 addresses. There are 2 types of addresses : Unicast — An identifier for a single interface.


2 Answers

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

like image 198
erickson Avatar answered Sep 24 '22 05:09

erickson


I have a real old version but this worked for me,

public int getPort(SocketAddress address) {
    return ((InetSocketAddress) address).getPort();
}
like image 31
ZZ Coder Avatar answered Sep 21 '22 05:09

ZZ Coder