How can I remove the current process/application which is already assigned to a port?
For example: localhost:8080
Step 1:
Open up cmd.exe (note: you may need to run it as an administrator, but this isn't always necessary), then run the below command:
netstat -ano | findstr :<PORT>
(Replace <PORT>
with the port number you want, but keep the colon)
The area circled in red shows the PID (process identifier). Locate the PID of the process that's using the port you want.
Step 2:
Next, run the following command:
taskkill /PID <PID> /F
(No colon this time)
Lastly, you can check whether the operation succeeded or not by re-running the command in "Step 1". If it was successful you shouldn't see any more search results for that port number.
Result for windows
In my case 8080 is the port I wants to kill
And 18264 is the PID listening to the port 8080
So the task you have to kill is the pid for the particular port
C:\Users\Niroshan>netstat -ano|findstr "PID :8080"
Proto Local Address Foreign Address State PID
TCP 0.0.0.0:8080 0.0.0.0:0 LISTENING 18264
taskkill /pid 18264 /f
Here is a script to do it in WSL2
PIDS=$(cmd.exe /c netstat -ano | cmd.exe /c findstr :$1 | awk '{print $5}')
for pid in $PIDS
do
cmd.exe /c taskkill /PID $pid /F
done
For use in command line:
for /f "tokens=5" %a in ('netstat -aon ^| find ":8080" ^| find "LISTENING"') do taskkill /f /pid %a
For use in bat-file:
for /f "tokens=5" %%a in ('netstat -aon ^| find ":8080" ^| find "LISTENING"') do taskkill /f /pid %%a
If you're using Windows Terminal then the killing process might be little less tedious.
I've been using windows terminal and kill PID
works fine for me to kill processes on the port as the new Windows Terminal supports certain bash commands. For example: kill 13300
So, the complete process will look like this-
netstat -ano | findstr :PORT
kill PID
For Example:
PS C:\Users\username> netstat -ano | findstr :4445
TCP 0.0.0.0:4445 0.0.0.0:0 LISTENING 7368
TCP [::]:4445 [::]:0 LISTENING 7368
PS C:\Users\username> kill 7368
PS C:\Users\username> netstat -ano | findstr :4445
PS C:\Users\username>
See when I typed the first command to list processes on the port it returned empty. That means all processes are killed now.
If you already know the port number, it will probably suffice to send a software termination signal to the process (SIGTERM):
kill $(lsof -t -i :PORT_NUMBER)