Find the PID of a process that uses a port on Windows
Find the PID of a process that uses 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 administrator) to kill some certain processes
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
Command:
netstat -aon | findstr 4723
Output:
TCP 0.0.0.0:4723 0.0.0.0:0 LISTENING 10396
Now cut the process ID, "10396", using the 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 the 4th number of the value means "LISTENING" then command in Windows.
Command:
for /f "tokens=4" %a in ('netstat -aon ^| findstr 4723') do @echo %~nxa
Output:
LISTENING
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.