Search code examples
javasocketsserverinetaddress

How to get listening server port in Java?


My application is deployed in websphere server and from java code, I need to get listening port of the server.

NOTE: I am using below line for getting internal host name of the system. InetAddress.getLocalHost().getHostName();

EDIT: Our server is running on local port 30036 and a local host name. We cannot connect this server using these host and port from out side. We have separate public host/port for outside connection. But in our scenario, we want to access a service running on the same server from the java code. Any way to get this internal port dynamically?


Solution

  • You should be able to access request.getLocalPort() in your service methods (get, post, service, etc). That will tell you what port the request came in on. It's possible it got changed during routing somewhere, and that the port the server is listening on isn't exactly what the client knows about, but if that's the case there's absolutely no where for the server to be able to know that.