Débora
Débora

Reputation: 5952

Getting the process name for a given Port in Java on Ubuntu-Linux?

I want to get the process name for the given PORT ID in Java, Ubuntu. I found samples how to do it in windows(tasklist in RunTime). But I need to know this in Linux.

Upvotes: 1

Views: 825

Answers (2)

Dr. Jan-Philip Gehrcke
Dr. Jan-Philip Gehrcke

Reputation: 35806

The /proc file system helps. /proc/$PID/exe is a symbolic link to the executable corresponding to the process ID. Obviously, you can simply read that file from Java.

Edit: Before, you asked for "process ID", now it is about a TCP/IP port... that renders my answer useless.

Upvotes: 2

chresse
chresse

Reputation: 5815

If you want to list the application which listens to a certain port, you can use the unix command lsof in combination with awk:

lsof -i :80 | awk '{print $1}'

This will list you i.e. the commandname from the process which listens to port 80.

In your javacode you have write following:

int port = 80;
Process p = Runtime.getRuntime().exec("lsof -i :" + port + " | awk '{print $1}'");

BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
while ((s = reader.readLine()) != null) {
    System.out.println(s);
}

Note that if you want to get a process name based on a process id (PID), you can use this instead:

Process p = Runtime.getRuntime().exec("ps -ef | awk '{if($2==\"" + pid + "\") print $8}'");

Upvotes: 4

Related Questions