Find PID of process that use a port on Windows

2019-01-10 00:04发布

问题:

My service crash on startup with the classic :

java.rmi.server.ExportException: Listen failed on port: 9999

How can I find the process for killing it?

回答1:

Just open a command shell and type : (saying your port is 123456)

netstat -a -n -o | find "123456"

You will see everything you need

The headers are :

 Proto  Local Address          Foreign Address        State           PID
 TCP    0.0.0.0:37             0.0.0.0:0              LISTENING       1111


回答2:

Find PID of process that use a port on Windows (e.g. port:"9999")
netstat -aon | find "9999"

-a Displays all connections and listening ports.

-o Displays the owning process ID associated with each connection.

-n Displays addresses and port numbers in numerical form.

output:
TCP 0.0.0.0:9999 0.0.0.0:0 LISTENING 15776

Then Kill the process by PID taskkill /F /PID 15776

/F - Specifies to forcefully terminate the process(es).

Note: You may need an extra permission (run from admin) to kill some certain processes



回答3:

After some fiddling with a script I came to this action. Copy and save it in a .bat file:

FOR /F "usebackq tokens=5" %%i IN (`netstat -aon ^| find "3306"`) DO taskkill /F /PID %%i

change 'find "3306"' in the port number which needs to be free. Then run the file as admin. It will kill all the processes running on this port



回答4:

If you want to do this programmatically you can use some of the options given to you as follows in a PowerShell script:

$processPID =  $($(netstat -aon | findstr "9999")[0] -split '\s+')[-1]
taskkill /f /pid $processPID

However; be aware that the more accurate you can be the more precise your PID result will be. If you know which host the port is supposed to be on you can narrow it down a lot. netstat -aon | findstr "0.0.0.0:9999" will only return one application and most llikely the correct one. Only searching on the port number may cause you to return processes that only happens to have 9999 in it, like this:

TCP    0.0.0.0:9999                        0.0.0.0:0       LISTENING       15776
UDP    [fe80::81ad:9999:d955:c4ca%2]:1900  *:*                             12331

The most likely candidate usually ends up first, but if the process has ended before you run your script you may end up with PID 12331 instead and killing the wrong process.



回答5:

This helps to find PID using port number.

lsof -i tcp:port_number


回答6:

command: netstat -aon | findstr 4723

output: TCP 0.0.0.0:4723 0.0.0.0:0 LISTENING 10396

now cut process id "10396" using for command in windows.

command: for /f "tokens=5" %a in ('netstat -aon ^| findstr 4723') do @echo %~nxa

output: 10396

if you want to cut 4th number of value means "LISTENING" then command in windows.

command: for /f "tokens=4" %a in ('netstat -aon ^| findstr 4723') do @echo %~nxa

output: LISTENING

I hope my answer helps you!!



标签: port