Running on windows.
I need to know from within my program which processes (like Skype) are running on port :80.
I should be able to get the PID of the process running on port :80 via
netstat -o -n -a | findstr 0.0:80.
What would be the best way to get the name of a process with a given PID from within Java?
If there is any way to get the name of the process running on port :80 from within Java I would prefere that also.
The reason I need this is that my application launches a jetty web server which uses port :80. I want to warn the user that an other service is already running port :80 in case.
If you use Java 10 or above, the enhanced process API can help you use PID to obtain the process name (Or other process information), such as:
import java.io.File;
class Scratch {
public static void main(String[] args) {
// Tips: In actual use, you should check whether the value of option exists. The process may have ended at the time of acquisition.
// Obtain the processhandle corresponding to the process through the PID.
ProcessHandle processHandle = ProcessHandle.of(6312).orElseThrow();
// `processHandle.info().command()` will return the executable path of the process
String command = processHandle.info().command().orElseThrow();
System.out.println(command);
// Using File, you can obtain the executable file information later,
// or you can directly split the path to obtain the process name.
// System.out.println(command.substring(command.lastIndexOf(File.separator) + 1));
File exeFile = new File(command);
System.out.println(exeFile.getName());
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With