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

隐身守侯 提交于 2019-12-10 15:58:32

问题


Is there a way to find a port opened by java process, given the process id of the process in java? Need to find it using java as it has to be platform independent

Given a process id : output any port/socket connections being used by that process.

Few things given: Process running in same jvm. There is only 1 port/socket being used by that Process, for which the Pid is given.

Can not do platform specific commands like ps -au | grep pid | ...


回答1:


The answer is no. What processes have what ports is not information available to java applications at all. You'd need JNI and it would depend on the operating system.




回答2:


The answer is yes, depending on your operating system.

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

Here's some basic code that would do it:

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



回答3:


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 into the current thread name, then you could extract the port number from the thread name? e.g.

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 is:

port -> 51958
thread -> main:51958


来源:https://stackoverflow.com/questions/7289398/is-there-a-way-to-find-a-port-being-used-by-process-given-its-process-id-usin

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!