Is there a way to find the port used by a process given its process id using java?

Is there a way to find the port opened by a java process given the process id in java? You need to find it using java, since it must be platform independent.

Based on the process identifier: Displays any port / socket connections used by this process.

Few things: The process runs in the same jvm. This Process uses only 1 port / socket for which Pid is specified.

Unable to execute platform commands, such as ps -au | grep pid | ... ps -au | grep pid | ...

+4
source share
3 answers

The answer is no. Which processes have which ports are not information available for java applications. You will need JNI, and it will depend on the operating system.

+2
source

Have you tried jps? See http://download.oracle.com/javase/1.5.0/docs/tooldocs/share/jps.html

Would it help if you put the port number in the current stream name, could you extract the port number from the stream name? eg.

 import java.net.ServerSocket; public class SocketDriver { public static void main(String[] args) throws Exception { ServerSocket serverSocket = new ServerSocket(0); int localPort = serverSocket.getLocalPort(); String threadName = Thread.currentThread().getName(); Thread.currentThread().setName(threadName + ":" + localPort); System.out.println("port -> " + localPort); System.out.println("thread -> " + Thread.currentThread().getName()); serverSocket.close(); } } 

Output:

 port -> 51958 thread -> main:51958 
+1
source

The answer is yes, depending on your operating system.

You need to find the appropriate command, for example on mac osx, it lsof -i , then use Runtime to execute it and analyze the output.

Here is some basic code that would do this:

  Process p = Runtime.getRuntime().exec(new String[] { "lsof", "-i" }); InputStream commandOutput = p.getInputStream(); 
+1
source

All Articles