How to kill process on port windows

How can I remove the current process/application which is already assigned to a port?

For example: localhost:8080

Community's user avatar

asked Sep 22, 2016 at 7:19

KavinduWije's user avatar

4

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.

Mujeeb's user avatar

Mujeeb

1,0551 gold badge9 silver badges18 bronze badges

answered Sep 22, 2016 at 7:59

KavinduWije's user avatar

KavinduWijeKavinduWije

39.8k4 gold badges14 silver badges17 bronze badges

15

I know that is really old question, but found pretty easy to remember, fast command to kill apps that are using port.

Requirements: [email protected]^ version

npx kill-port 8080

You can also read more about kill-port here: https://www.npmjs.com/package/kill-port

answered Jun 16, 2020 at 10:32

Rafał Figura's user avatar

Rafał FiguraRafał Figura

5,5461 gold badge15 silver badges20 bronze badges

3

There are two ways to kill the processes

Option 01 — Simplest and easiest

Requirement : [email protected]^ version

Open the Command prompt as Administrator and give the following command with the port (Here the port is 8080)

npx kill-port 8080

Option 02 — Most commonly used

  • Step 01

    Open Windows command prompt as Administrator

  • Step 02

    Find the PID of the port you want to kill with the below command: Here port is 8080

netstat -ano|findstr "PID :8080"

TCP 0.0.0.0:8080 0.0.0.0:0 LISTENING 18264

  • Step 03

    Kill the PID you received above with the below command (In my case PID is 18264)

taskkill /PID 18264 /f

answered Jul 21, 2020 at 4:16

Niroshan Ratnayake's user avatar

1

Step 1 (same is in accepted answer written by KavinduWije):

netstat -ano | findstr :yourPortNumber

Change in Step 2 to:

tskill typeyourPIDhere 

Note: taskkill is not working in some git bash terminal

Community's user avatar

answered Sep 21, 2017 at 11:20

afsarkhan10182's user avatar

afsarkhan10182afsarkhan10182

2,1721 gold badge13 silver badges17 bronze badges

1

With Windows 10/11 default tools:

✔ Step one:

Open Windows PowerShell as Administrator

✔ Step two:

Find the ProcessID for the port you need to kill (e.g. 3000)

netstat -aon | findstr 3000

TCP 0.0.0.0:3000 LISTEN 1234

✔ Step three:

Kill the zombie process:

taskkill /f /pid 1234

where «1234» is your ProcessID (aka PID)

*Extra tip if you use Windows Subsystem for Linux (Ubuntu WSL):

✔ Step one:

sudo lsof -t -i:3000

✔ Step two:

sudo kill -9 1234

answered Mar 18, 2019 at 10:01

Java wanna bee's user avatar

Java wanna beeJava wanna bee

2,6021 gold badge12 silver badges25 bronze badges

4

If you are using GitBash

Step one:

netstat -ano | findstr :8080

Step two:

taskkill /PID typeyourPIDhere /F 

(/F forcefully terminates the process)

Uchenna Nwanyanwu's user avatar

answered Sep 17, 2017 at 19:55

Ara Yaghsizian's user avatar

Ara YaghsizianAra Yaghsizian

1,2891 gold badge8 silver badges10 bronze badges

1

The simplest solution — the only one I can ever remember:

In Windows Powershell

Say we want to stop a process on port 8080

  1. Get the process:
netstat -ano | findstr :8080
  1. Stop the process
stop-process 82932

answered Sep 3, 2021 at 15:38

Luke Garrigan's user avatar

Luke GarriganLuke Garrigan

4,6111 gold badge21 silver badges31 bronze badges

2

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)

answered Dec 19, 2018 at 7:43

Fellow Stranger's user avatar

Fellow StrangerFellow Stranger

32.3k35 gold badges170 silver badges233 bronze badges

4

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

marvedly's user avatar

answered Jun 29, 2018 at 10:10

Mahesh Narwade's user avatar

4

Simple CMD is working me. Easy to remember

find the port number which you want kill and run the below cmd

npx kill-port 8080

After complete the Port get stopped and getting this message

npx: installed 3 in 13.796s
Process on port 8080 killed

ux.engineer's user avatar

ux.engineer

10.2k14 gold badges67 silver badges112 bronze badges

answered Apr 28, 2021 at 7:45

Deepak's user avatar

DeepakDeepak

5717 silver badges19 bronze badges

0

In Windows PowerShell version 1 or later to stop a process on port 3000 type:

Stop-Process (,(netstat -ano | findstr :3000).split() | foreach {$[$.length-1]}) -Force


As suggested by @morganpdx here`s a more PowerShell-ish, better version:

Stop-Process -Id (Get-NetTCPConnection -LocalPort 3000).OwningProcess -Force

answered Dec 8, 2017 at 15:54

todorm's user avatar

todormtodorm

4744 silver badges6 bronze badges

3

Open command prompt and issue below command

netstat -ano|findstr "PID :8888"

Output will show the process id occupying the port

enter image description here

Issue below command to kill the PID

taskkill /pid 8912 /f

You will receive the output as below

SUCCESS: The process with PID 8860 has been terminated.

answered Mar 31, 2021 at 13:08

Waqas Ahmed's user avatar

Waqas AhmedWaqas Ahmed

4,8313 gold badges37 silver badges45 bronze badges

1

If you can use PowerShell on Windows you just need :

Get-Process -Id (Get-NetTCPConnection -LocalPort "8080").OwningProcess | Stop-Process

answered Oct 27, 2020 at 10:20

Emanuele Fricano's user avatar

2

For Windows users, you can use the CurrPorts tool to kill ports under usage easily:

Enter image description here

Peter Mortensen's user avatar

answered Oct 3, 2018 at 11:43

Zuhair Taha's user avatar

Zuhair TahaZuhair Taha

2,8382 gold badges35 silver badges33 bronze badges

1

I was running zookeeper on Windows and wasn’t able to stop ZooKeeper running at 2181 port using zookeeper-stop.sh, so tried this double slash «//» method to taskkill. It worked

     1. netstat -ano | findstr :2181
       TCP    0.0.0.0:2181           0.0.0.0:0              LISTENING       8876
       TCP    [::]:2181              [::]:0                 LISTENING       8876

     2.taskkill //PID 8876 //F
       SUCCESS: The process with PID 8876 has been terminated.

Peter Mortensen's user avatar

answered Dec 6, 2018 at 4:29

driven_spider's user avatar

Let’s Automate!

If you fall into this issue much often like me, make an .bat file and run it to end process.

create a bat file «killport.bat»

set /P port="Enter port : "
echo showing process running with port %port%

netstat -ano|findstr "PID :%port%"

set /P pid="Enter PID to kill : "

taskkill /pid %pid% /f

set /P exit="Press any key to exit..."

Run this file by double clicking and

  1. Enter port number (then it will list process with PID)
  2. Enter PID to kill

Done

(Optional)

Set to path environment so that you can access this file from anywhere.

Most probably you will know how to add an new path to env. But here’s how if you don’t

Step 1 of 4

Search ENV on start menu

enter image description here

Step 2 of 4

Select Environment Variables

enter image description here

Step 3 of 4

Select ‘path’ and click Edit button

enter image description here

Step 4 of 4

Click ‘New’ add the path where .bat file is stored. Since I saved it on ‘../Documents/bats’ folder I am adding this path. Your path will depend on where you save this file.

enter image description here

Open CMD and test. Remember you filename will the word to run this file. Since I saved the .bat file as ‘killport.bat’ => ‘killport’ is the word to run it.

enter image description here
if do enjoy!
else share how you done it here

Dharman's user avatar

Dharman

31.1k25 gold badges87 silver badges138 bronze badges

answered May 10, 2021 at 10:46

Abhin Krishna KA's user avatar

Run cmd as administrator. Then type this code in there.

netstat -ano | findstr :<8080>

Then you can see the PID run on your port. Then copy that PID number. ( PID is a unique number that helps identify a hardware product or a registered software product.) And type below code line and press enter.

taskkill /PID <Enter the copied PID Number> /F

answered Jun 10, 2021 at 18:13

Chandima Samarakoon's user avatar

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-

  • Open Windows Terminal
  • Type the following command to show processes running on the port you’re looking to kill processes.
    netstat -ano | findstr :PORT
  • Type following to kill the process.
    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.

Update: kill is an alias for Stop-Process. Thanks, @FSCKur for letting us know.

answered May 21, 2020 at 9:55

lazycipher's user avatar

lazycipherlazycipher

3403 silver badges14 bronze badges

7

If you use powershell 7+ this worked for me. Just add this function in your $PROFILE file.

function killport([parameter(mandatory)] [string] $uport){
    if($upid = (Get-NetTCPConnection -LocalPort $uport -ErrorAction Ignore).OwningProcess){kill $upid}
}

then simply use killport 8080

or if you prefer just the command you can try this:

kill $(Get-NetTCPConnection -LocalPort 8761 -ErrorAction Ignore).OwningProcess

answered Feb 1, 2022 at 19:19

Deekshith Anand's user avatar

Deekshith AnandDeekshith Anand

2,2431 gold badge22 silver badges24 bronze badges

4

You can do by run a bat file:

@ECHO OFF                                                                              
FOR /F "tokens=5" %%T IN ('netstat -a -n -o ^| findstr "9797" ') DO (
SET /A ProcessId=%%T) &GOTO SkipLine                                                   
:SkipLine                                                                              
echo ProcessId to kill = %ProcessId%
taskkill /f /pid %ProcessId%
PAUSE

answered Dec 5, 2018 at 7:53

flopcoder's user avatar

flopcoderflopcoder

1,19512 silver badges26 bronze badges

the first step

netstat -vanp tcp | grep 8888

example

tcp4     0      0    127.0.0.1.8888   *.*    LISTEN      131072 131072  76061    0
tcp46    0      0    *.8888           *.*    LISTEN      131072 131072  50523    0

the second step: find your PIDs and kill them

in my case

sudo kill -9 76061 50523

answered Aug 25, 2020 at 19:35

ruscon's user avatar

rusconruscon

772 silver badges9 bronze badges

1

netstat -ano | findstr :PORT
kill PI

answered Oct 30, 2020 at 11:31

harun ugur's user avatar

harun ugurharun ugur

1,72620 silver badges19 bronze badges

One line solution using GitBash:

 tskill `netstat -ano | grep LISTENING | findstr :8080 | sed -r 's/(\s+[^\s]+){4}(.*)/\1/'`

Replace 8080 with the port your server is listening to.

If you need to use it often, try adding to your ~/.bashrc the function:

function killport() {
        tskill `netstat -ano | findstr LISTENING | findstr :$1 | sed -r 's/^(\s+[^\s]+){4}(\d*)$/\1/'`
}

and simply run

killport 8080

answered May 20, 2020 at 21:04

Italo Borssatto's user avatar

Italo BorssattoItalo Borssatto

15.1k7 gold badges63 silver badges88 bronze badges

2

I wrote a tiny node js script for this. Just run it like this:
node killPort.js 8080 or whatever port you need to kill. Save the following to a killPort.js file:

const { exec } = require('child_process');
const fs = require(`fs`);

const port = process.argv.length > 2 ? process.argv[2] : ``;
if (!port || isNaN(port)) console.log(`port is required as an argument and has to be a number`);
else {
    exec(`netstat -ano | findstr :${port}`, (err, stdout, stderr) => {
        if (!stdout) console.log(`nobody listens on port ${port}`);
        else {
            const res = stdout.split(`\n`).map(s => s.trim());
            const pid = res.map(s => s.split(` `).pop()).filter(s => s).pop();
            console.log(`Listener of ${port} is found, its pid is ${pid}, killing it...`);
            exec(`taskkill /PID ${pid} /F`, (err, stdout, stderr) => {
                if (!stdout) console.log(`we tried to kill it, but not sure about the result, please run me again`);
                else console.log(stdout);
            })
        }
    });
}

answered Aug 31, 2021 at 9:11

shal's user avatar

shalshal

2,8544 gold badges20 silver badges31 bronze badges

1

I am using GitBash and I error like below when ran

taskkill //PID XXXX

ERROR: The process with PID 7420 could not be terminated. Reason: This
process can only be terminated forcefully (with /F option).

So used //F like below and worked fine

taskkill //F //PID XXXX

answered Dec 25, 2021 at 11:29

Vatsal Shah's user avatar

Vatsal ShahVatsal Shah

1,33418 silver badges21 bronze badges

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

answered Aug 14, 2020 at 9:59

MyrionSC2's user avatar

MyrionSC2MyrionSC2

1,2481 gold badge14 silver badges24 bronze badges

We can avoid this by simple restarting IIS, using the below command:

IISRESET

Peter Mortensen's user avatar

answered Aug 21, 2018 at 12:31

ksrider 148's user avatar

0

How can I remove the current process/application which is already assigned to a port?

For example: localhost:8080

Community's user avatar

asked Sep 22, 2016 at 7:19

KavinduWije's user avatar

4

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.

Mujeeb's user avatar

Mujeeb

1,0551 gold badge9 silver badges18 bronze badges

answered Sep 22, 2016 at 7:59

KavinduWije's user avatar

KavinduWijeKavinduWije

39.8k4 gold badges14 silver badges17 bronze badges

15

I know that is really old question, but found pretty easy to remember, fast command to kill apps that are using port.

Requirements: [email protected]^ version

npx kill-port 8080

You can also read more about kill-port here: https://www.npmjs.com/package/kill-port

answered Jun 16, 2020 at 10:32

Rafał Figura's user avatar

Rafał FiguraRafał Figura

5,5461 gold badge15 silver badges20 bronze badges

3

There are two ways to kill the processes

Option 01 — Simplest and easiest

Requirement : [email protected]^ version

Open the Command prompt as Administrator and give the following command with the port (Here the port is 8080)

npx kill-port 8080

Option 02 — Most commonly used

  • Step 01

    Open Windows command prompt as Administrator

  • Step 02

    Find the PID of the port you want to kill with the below command: Here port is 8080

netstat -ano|findstr "PID :8080"

TCP 0.0.0.0:8080 0.0.0.0:0 LISTENING 18264

  • Step 03

    Kill the PID you received above with the below command (In my case PID is 18264)

taskkill /PID 18264 /f

answered Jul 21, 2020 at 4:16

Niroshan Ratnayake's user avatar

1

Step 1 (same is in accepted answer written by KavinduWije):

netstat -ano | findstr :yourPortNumber

Change in Step 2 to:

tskill typeyourPIDhere 

Note: taskkill is not working in some git bash terminal

Community's user avatar

answered Sep 21, 2017 at 11:20

afsarkhan10182's user avatar

afsarkhan10182afsarkhan10182

2,1721 gold badge13 silver badges17 bronze badges

1

With Windows 10/11 default tools:

✔ Step one:

Open Windows PowerShell as Administrator

✔ Step two:

Find the ProcessID for the port you need to kill (e.g. 3000)

netstat -aon | findstr 3000

TCP 0.0.0.0:3000 LISTEN 1234

✔ Step three:

Kill the zombie process:

taskkill /f /pid 1234

where «1234» is your ProcessID (aka PID)

*Extra tip if you use Windows Subsystem for Linux (Ubuntu WSL):

✔ Step one:

sudo lsof -t -i:3000

✔ Step two:

sudo kill -9 1234

answered Mar 18, 2019 at 10:01

Java wanna bee's user avatar

Java wanna beeJava wanna bee

2,6021 gold badge12 silver badges25 bronze badges

4

If you are using GitBash

Step one:

netstat -ano | findstr :8080

Step two:

taskkill /PID typeyourPIDhere /F 

(/F forcefully terminates the process)

Uchenna Nwanyanwu's user avatar

answered Sep 17, 2017 at 19:55

Ara Yaghsizian's user avatar

Ara YaghsizianAra Yaghsizian

1,2891 gold badge8 silver badges10 bronze badges

1

The simplest solution — the only one I can ever remember:

In Windows Powershell

Say we want to stop a process on port 8080

  1. Get the process:
netstat -ano | findstr :8080
  1. Stop the process
stop-process 82932

answered Sep 3, 2021 at 15:38

Luke Garrigan's user avatar

Luke GarriganLuke Garrigan

4,6111 gold badge21 silver badges31 bronze badges

2

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)

answered Dec 19, 2018 at 7:43

Fellow Stranger's user avatar

Fellow StrangerFellow Stranger

32.3k35 gold badges170 silver badges233 bronze badges

4

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

marvedly's user avatar

answered Jun 29, 2018 at 10:10

Mahesh Narwade's user avatar

4

Simple CMD is working me. Easy to remember

find the port number which you want kill and run the below cmd

npx kill-port 8080

After complete the Port get stopped and getting this message

npx: installed 3 in 13.796s
Process on port 8080 killed

ux.engineer's user avatar

ux.engineer

10.2k14 gold badges67 silver badges112 bronze badges

answered Apr 28, 2021 at 7:45

Deepak's user avatar

DeepakDeepak

5717 silver badges19 bronze badges

0

In Windows PowerShell version 1 or later to stop a process on port 3000 type:

Stop-Process (,(netstat -ano | findstr :3000).split() | foreach {$[$.length-1]}) -Force


As suggested by @morganpdx here`s a more PowerShell-ish, better version:

Stop-Process -Id (Get-NetTCPConnection -LocalPort 3000).OwningProcess -Force

answered Dec 8, 2017 at 15:54

todorm's user avatar

todormtodorm

4744 silver badges6 bronze badges

3

Open command prompt and issue below command

netstat -ano|findstr "PID :8888"

Output will show the process id occupying the port

enter image description here

Issue below command to kill the PID

taskkill /pid 8912 /f

You will receive the output as below

SUCCESS: The process with PID 8860 has been terminated.

answered Mar 31, 2021 at 13:08

Waqas Ahmed's user avatar

Waqas AhmedWaqas Ahmed

4,8313 gold badges37 silver badges45 bronze badges

1

If you can use PowerShell on Windows you just need :

Get-Process -Id (Get-NetTCPConnection -LocalPort "8080").OwningProcess | Stop-Process

answered Oct 27, 2020 at 10:20

Emanuele Fricano's user avatar

2

For Windows users, you can use the CurrPorts tool to kill ports under usage easily:

Enter image description here

Peter Mortensen's user avatar

answered Oct 3, 2018 at 11:43

Zuhair Taha's user avatar

Zuhair TahaZuhair Taha

2,8382 gold badges35 silver badges33 bronze badges

1

I was running zookeeper on Windows and wasn’t able to stop ZooKeeper running at 2181 port using zookeeper-stop.sh, so tried this double slash «//» method to taskkill. It worked

     1. netstat -ano | findstr :2181
       TCP    0.0.0.0:2181           0.0.0.0:0              LISTENING       8876
       TCP    [::]:2181              [::]:0                 LISTENING       8876

     2.taskkill //PID 8876 //F
       SUCCESS: The process with PID 8876 has been terminated.

Peter Mortensen's user avatar

answered Dec 6, 2018 at 4:29

driven_spider's user avatar

Let’s Automate!

If you fall into this issue much often like me, make an .bat file and run it to end process.

create a bat file «killport.bat»

set /P port="Enter port : "
echo showing process running with port %port%

netstat -ano|findstr "PID :%port%"

set /P pid="Enter PID to kill : "

taskkill /pid %pid% /f

set /P exit="Press any key to exit..."

Run this file by double clicking and

  1. Enter port number (then it will list process with PID)
  2. Enter PID to kill

Done

(Optional)

Set to path environment so that you can access this file from anywhere.

Most probably you will know how to add an new path to env. But here’s how if you don’t

Step 1 of 4

Search ENV on start menu

enter image description here

Step 2 of 4

Select Environment Variables

enter image description here

Step 3 of 4

Select ‘path’ and click Edit button

enter image description here

Step 4 of 4

Click ‘New’ add the path where .bat file is stored. Since I saved it on ‘../Documents/bats’ folder I am adding this path. Your path will depend on where you save this file.

enter image description here

Open CMD and test. Remember you filename will the word to run this file. Since I saved the .bat file as ‘killport.bat’ => ‘killport’ is the word to run it.

enter image description here
if do enjoy!
else share how you done it here

Dharman's user avatar

Dharman

31.1k25 gold badges87 silver badges138 bronze badges

answered May 10, 2021 at 10:46

Abhin Krishna KA's user avatar

Run cmd as administrator. Then type this code in there.

netstat -ano | findstr :<8080>

Then you can see the PID run on your port. Then copy that PID number. ( PID is a unique number that helps identify a hardware product or a registered software product.) And type below code line and press enter.

taskkill /PID <Enter the copied PID Number> /F

answered Jun 10, 2021 at 18:13

Chandima Samarakoon's user avatar

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-

  • Open Windows Terminal
  • Type the following command to show processes running on the port you’re looking to kill processes.
    netstat -ano | findstr :PORT
  • Type following to kill the process.
    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.

Update: kill is an alias for Stop-Process. Thanks, @FSCKur for letting us know.

answered May 21, 2020 at 9:55

lazycipher's user avatar

lazycipherlazycipher

3403 silver badges14 bronze badges

7

If you use powershell 7+ this worked for me. Just add this function in your $PROFILE file.

function killport([parameter(mandatory)] [string] $uport){
    if($upid = (Get-NetTCPConnection -LocalPort $uport -ErrorAction Ignore).OwningProcess){kill $upid}
}

then simply use killport 8080

or if you prefer just the command you can try this:

kill $(Get-NetTCPConnection -LocalPort 8761 -ErrorAction Ignore).OwningProcess

answered Feb 1, 2022 at 19:19

Deekshith Anand's user avatar

Deekshith AnandDeekshith Anand

2,2431 gold badge22 silver badges24 bronze badges

4

You can do by run a bat file:

@ECHO OFF                                                                              
FOR /F "tokens=5" %%T IN ('netstat -a -n -o ^| findstr "9797" ') DO (
SET /A ProcessId=%%T) &GOTO SkipLine                                                   
:SkipLine                                                                              
echo ProcessId to kill = %ProcessId%
taskkill /f /pid %ProcessId%
PAUSE

answered Dec 5, 2018 at 7:53

flopcoder's user avatar

flopcoderflopcoder

1,19512 silver badges26 bronze badges

the first step

netstat -vanp tcp | grep 8888

example

tcp4     0      0    127.0.0.1.8888   *.*    LISTEN      131072 131072  76061    0
tcp46    0      0    *.8888           *.*    LISTEN      131072 131072  50523    0

the second step: find your PIDs and kill them

in my case

sudo kill -9 76061 50523

answered Aug 25, 2020 at 19:35

ruscon's user avatar

rusconruscon

772 silver badges9 bronze badges

1

netstat -ano | findstr :PORT
kill PI

answered Oct 30, 2020 at 11:31

harun ugur's user avatar

harun ugurharun ugur

1,72620 silver badges19 bronze badges

One line solution using GitBash:

 tskill `netstat -ano | grep LISTENING | findstr :8080 | sed -r 's/(\s+[^\s]+){4}(.*)/\1/'`

Replace 8080 with the port your server is listening to.

If you need to use it often, try adding to your ~/.bashrc the function:

function killport() {
        tskill `netstat -ano | findstr LISTENING | findstr :$1 | sed -r 's/^(\s+[^\s]+){4}(\d*)$/\1/'`
}

and simply run

killport 8080

answered May 20, 2020 at 21:04

Italo Borssatto's user avatar

Italo BorssattoItalo Borssatto

15.1k7 gold badges63 silver badges88 bronze badges

2

I wrote a tiny node js script for this. Just run it like this:
node killPort.js 8080 or whatever port you need to kill. Save the following to a killPort.js file:

const { exec } = require('child_process');
const fs = require(`fs`);

const port = process.argv.length > 2 ? process.argv[2] : ``;
if (!port || isNaN(port)) console.log(`port is required as an argument and has to be a number`);
else {
    exec(`netstat -ano | findstr :${port}`, (err, stdout, stderr) => {
        if (!stdout) console.log(`nobody listens on port ${port}`);
        else {
            const res = stdout.split(`\n`).map(s => s.trim());
            const pid = res.map(s => s.split(` `).pop()).filter(s => s).pop();
            console.log(`Listener of ${port} is found, its pid is ${pid}, killing it...`);
            exec(`taskkill /PID ${pid} /F`, (err, stdout, stderr) => {
                if (!stdout) console.log(`we tried to kill it, but not sure about the result, please run me again`);
                else console.log(stdout);
            })
        }
    });
}

answered Aug 31, 2021 at 9:11

shal's user avatar

shalshal

2,8544 gold badges20 silver badges31 bronze badges

1

I am using GitBash and I error like below when ran

taskkill //PID XXXX

ERROR: The process with PID 7420 could not be terminated. Reason: This
process can only be terminated forcefully (with /F option).

So used //F like below and worked fine

taskkill //F //PID XXXX

answered Dec 25, 2021 at 11:29

Vatsal Shah's user avatar

Vatsal ShahVatsal Shah

1,33418 silver badges21 bronze badges

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

answered Aug 14, 2020 at 9:59

MyrionSC2's user avatar

MyrionSC2MyrionSC2

1,2481 gold badge14 silver badges24 bronze badges

We can avoid this by simple restarting IIS, using the below command:

IISRESET

Peter Mortensen's user avatar

answered Aug 21, 2018 at 12:31

ksrider 148's user avatar

0

If you’re using Windows 11 and encounter a situation where a process is causing issues and occupying a specific port, you might need to terminate that process to free up the port for other applications. Killing a process on a specific port can be done using various methods in Windows 11. In this article, we’ll explore several techniques to accomplish this task, ranging from built-in tools to third-party applications.

Understanding Processes and Ports

Before we dive into the methods to kill a process on a specific port, let’s briefly understand what processes and ports are.

Processes

A process is an instance of a running program on your computer. Each process has its own unique identifier, known as the Process ID (PID), and it may use network resources, such as ports, to communicate with other processes or devices.

Ports

In the context of networking, a port is a communication endpoint that processes use to exchange data over a network. Ports are identified by a numeric value, known as the port number. Common applications use specific port numbers, such as port 80 for HTTP or port 443 for HTTPS.

Using Command Prompt (CMD) or PowerShell

Both Command Prompt and PowerShell are powerful command-line tools built into Windows 11. They allow users to execute various commands, including those to manage processes.

Method 1: Using Tasklist and Taskkill (CMD)

  1. Identify the PID of the Process

    Open Command Prompt by searching for “cmd” in the Start menu, and then run the following command to find the PID of the process using the specific port (replace PORT_NUMBER with the port number):

    arduino

    tasklist | findstr "LISTENING"

    This will display a list of processes that are currently listening on ports. Look for the process using the desired port number and note its PID.

  2. Kill the Process

    Once you have the PID of the process, you can terminate it using the following command (replace PID with the actual PID):

    The /F flag forces the process to terminate forcefully.

Method 2: Using Get-NetTCPConnection and Stop-Process (PowerShell)

  1. Open PowerShell

    Search for “PowerShell” in the Start menu, right-click on “Windows PowerShell,” and select “Run as administrator” to open an elevated PowerShell session.

  2. Identify the PID of the Process

    Execute the following command to list all TCP connections and filter them based on the desired port number:

    vbnet

    Get-NetTCPConnection | Where-Object {$_.LocalPort -eq PORT_NUMBER}

    Note the PID of the process you want to terminate.

  3. Kill the Process

    To terminate the process using its PID, run the following command (replace PID with the actual PID):

    arduino

    Stop-Process -Id PID -Force

    The -Force flag ensures that the process is forcefully terminated.

Using Resource Monitor

Windows 11 includes a useful tool called Resource Monitor, which provides an in-depth view of your system’s resources, including processes and network activity.

  1. Open Resource Monitor

    To open Resource Monitor, you can use any of the following methods:

    • Press Win + R to open the Run dialog, type resmon.exe, and press Enter.
    • Search for “Resource Monitor” in the Start menu and click on the app in the search results.
  2. Locate the Process

    In Resource Monitor, switch to the “Network” tab. Look for the port number you want to release under the “Listening Ports” section. The associated process will be listed in the “Process” column.

  3. Terminate the Process

    Once you’ve identified the process, right-click on it and select “End Process.” Confirm the action when prompted.

Resource Monitor provides a visual representation of resource usage, making it easier to spot processes that might be causing performance issues or using specific ports.

Using Third-Party Applications

If you prefer a more user-friendly approach or need additional features, third-party applications can help manage processes and ports efficiently.

Method 1: Using TCPView

TCPView, developed by Sysinternals (now a part of Microsoft), is a popular tool that provides a real-time view of all TCP and UDP connections on your system. It allows you to terminate processes and close network connections easily.

  1. Download and Install TCPView

    Visit the Microsoft Sysinternals website and download TCPView.

  2. Launch TCPView

    After installing TCPView, run the application as an administrator. You will see a list of all active connections, including the processes associated with each connection.

  3. Identify and Terminate the Process

    Locate the process using the port you want to free up. Right-click on the process and select “End Process” to terminate it.

Method 2: Using CurrPorts

CurrPorts is another free utility that displays a comprehensive list of all currently opened TCP/IP and UDP ports on your system. It provides details about each connection and allows you to close specific connections or terminate processes.

  1. Download and Install CurrPorts

    You can download CurrPorts from the NirSoft website. It’s a standalone application, so there’s no need to install it—simply run the executable.

  2. Run CurrPorts

    Launch CurrPorts with administrator privileges. The main window will display all active connections and their associated processes.

  3. Terminate the Process

    To kill a process, right-click on the desired connection and select “Close Selected TCP Connections” or “Close Selected UDP Connections.” You can also use the toolbar buttons for quick actions.

Conclusion

Knowing how to kill a process on a specific port can be valuable when dealing with networking issues and resource conflicts on your Windows 11 system. Whether you prefer built-in command-line tools or user-friendly third-party applications, Windows 11 offers various methods to identify and terminate troublesome processes.

Remember to use caution when terminating processes, especially system-critical ones, as it can potentially lead to instability or data loss. Always make sure you understand the consequences of terminating a process before taking any action.

By mastering these methods, you can effectively manage processes and ensure smooth operation for your applications and network connections on Windows 11.

Every process that is run on Windows uses a different port. So, suppose you’re trying to run an application that needs to utilize a particular port that is already in use. In that case, you may end up receiving an error message that goes something like – “Port 8080 is being used” or “The port number you provided is already in use.” 

The only way to get around this error is to manually kill the process that is occupying said port currently. The article below shows how you can identify which port is being used by which process and the different methods that will let you kill it so you can free up that port. 

How to find if a port is in use (and its associated process)

First up, open Command Prompt. Press Start, type cmd, right-click on ‘Command Prompt’, and select Run as administrator.

Type the following command to get a list of all the ports in use. 

netstat -ano

Press Enter.

You will now get a list of all the active ports on your system. The last few digits of an address (after the last colon) make up a port number. While its corresponding PID is the unique ID number of the process that is linked to it. 

To find if a specific port is in use, type the following command:

netstat -ano | findstr :port-number

Replace “port-number” with the actual port number and press Enter.

If it is in use, you will see a PID on the right, along with the words Listening or Established. 

To find the process, open Task Manager by pressing Ctrl+Shitf+Esc. Then look for the process with that PID. 

If you don’t see the PID column, right-click on one of the columns and select PID. 

Alternatively, you can make use of Resource Monitor to find the process. Press Start, type resource monitor and open it.

 

Expand Network and look for the process with the PID.

Here are a few ways that will allow you to identify which process is using which port and how to kill it.  

Method #1: Via Command Prompt

Once Command Prompt (as shown earlier) and type the following command:

To free up a port and kill the process associated with it, type in the following command:

taskkill /PID <type PID here> /f

Then press Enter. You should now get a message saying that the process has been terminated.

This method is the most commonly used method to find and kill processes that are on contentious ports such as port 8080 or 3000 which multiple processes and programs might want to access. 

Method #2: Via PowerShell

Terminating the process associated with the port can also be done via PowerShell. This is how:

Press Start, type Powershell, right-click on the result, and click on Run as administrator. 

Similarly to the Command Prompt, type the following command in PowerShell:

netstat -ano

Then Press Enter. You will get a list of all active connections.

Once you have the port, and its corresponding PID, you can know which process is linked to it (shown earlier). Take note of the PID that is using up a specific port.

To kill the process, type the following command:

taskkill /PID <enter PID here> /f

Press Enter. You will now get a message telling you that the process has been terminated. 

Method #3: Via Task Manager

This method works only if you know the PID that is linked to the port, for which purpose you will invariably have to go to refer to the command prompt or Powershell. But once you find the port and the PID associated with it, you can also end its associated process via Task Manager. Here’s how to do so. 

Press Ctrl+Shift+Esc to open up Task Manager. Here, if you don’t already see a PID tab, right-click on one of the tabs and select PID.

Now find the process that is associated with the PID that you want to kill. Right-click on the process and select End Task.

That’s it. You have now freed up the port that was linked to that process/PID.

Method #4: Via CurrPorts (Third Party Software)

There are a few third-party apps that let you kill a process that is associated with a port with just a click. One of them is CurrPorts, a free software that gets the job done in a jiffy.

Download: CurrPorts

On the aforementioned link, scroll down and click on Download CurrPorts.Once the file is downloaded, extract its contents and then run the cports.exe file. 

The main page of CurrPorts will provide you with all the information related to a given process, including its PID and the port being utilized. Simply right-click the process that you want to kill and select Kill Processes of Selected Ports.

Your port is now free. 

Though third-party applications abound, the Command Prompt and PowerShell are still one of the most used methods to kill a process on a port as they help to both identify and execute the process without any extraneous downloads. We hope the methods provided above allowed you to kill the processes on any given port on Windows 11. 

Каждый процесс, запущенный в Windows, использует другой порт. Итак, предположим, вы пытаетесь запустить приложение, которому необходимо использовать определенный порт, который уже используется. В этом случае вы можете получить сообщение об ошибке, которое выглядит примерно так: «Порт 8080 используется» или «Указанный вами номер порта уже используется».

Единственный способ обойти эту ошибку — вручную убить процесс, который в данный момент занимает указанный порт. В приведенной ниже статье показано, как определить, какой порт используется каким процессом, и различные методы, которые позволят вам убить его, чтобы вы могли освободить этот порт.

Как узнать, используется ли порт (и связанный с ним процесс)

Прежде всего, откройте командную строку. Нажмите «Пуск», введите cmd, щелкните правой кнопкой мыши «Командная строка» и выберите «Запуск от имени администратора».

Введите следующую команду, чтобы получить список всех используемых портов.

netstat -ано

Нажмите Ввод.

Теперь вы получите список всех активных портов в вашей системе. Последние несколько цифр адреса (после последнего двоеточия) составляют номер порта. В то время как его соответствующий PID является уникальным идентификационным номером процесса, который связан с ним.

Чтобы узнать, используется ли конкретный порт, введите следующую команду:

netstat -ано | findstr : номер порта

Замените «номер порта» фактическим номером порта и нажмите Enter.

Если он используется, справа вы увидите PID вместе со словами Listening или Established.

Чтобы найти процесс, откройте диспетчер задач, нажав Ctrl+Shitf+Esc. Затем найдите процесс с этим PID.

Если вы не видите столбец PID, щелкните правой кнопкой мыши один из столбцов и выберите PID.

Кроме того, вы можете использовать монитор ресурсов, чтобы найти процесс. Нажмите Пуск, введите монитор ресурсов и откройте его.

Разверните Network и найдите процесс с PID.

Как убить процесс в порту

Вот несколько способов, которые позволят вам определить, какой процесс использует какой порт и как его убить.

Способ №1: через командную строку

После командной строки (как показано ранее) и введите следующую команду:

Чтобы освободить порт и убить связанный с ним процесс, введите следующую команду:

taskkill /PID <введите здесь PID> /f

Затем нажмите Enter. Теперь вы должны получить сообщение о том, что процесс завершен.

Этот метод является наиболее часто используемым методом для поиска и уничтожения процессов, которые находятся на спорных портах, таких как порт 8080 или 3000, доступ к которым может потребоваться нескольким процессам и программам.

Способ №2: через PowerShell

Завершить процесс, связанный с портом, также можно с помощью PowerShell. Вот как:

Нажмите «Пуск», введите Powershell, щелкните правой кнопкой мыши результат и выберите «Запуск от имени администратора».

Аналогично командной строке введите в PowerShell следующую команду:

netstat -ано

Затем нажмите Enter. Вы получите список всех активных подключений.

Когда у вас есть порт и соответствующий ему PID, вы можете узнать, какой процесс связан с ним (показано ранее). Обратите внимание на PID, который использует определенный порт.

Чтобы убить процесс, введите следующую команду:

taskkill /PID <введите здесь PID> /f

Нажмите Ввод. Теперь вы получите сообщение о том, что процесс завершен.

Способ №3: через диспетчер задач

Этот метод работает только в том случае, если вы знаете PID, связанный с портом, для чего вам неизменно придется обращаться к командной строке или Powershell. Но как только вы найдете порт и связанный с ним PID, вы также можете завершить связанный с ним процесс через диспетчер задач. Вот как это сделать.

Нажмите Ctrl+Shift+Esc, чтобы открыть диспетчер задач. Здесь, если вы еще не видите вкладку PID, щелкните правой кнопкой мыши одну из вкладок и выберите PID.

Теперь найдите процесс, связанный с PID, который вы хотите убить. Щелкните правой кнопкой мыши процесс и выберите «Завершить задачу».

Вот и все. Теперь вы освободили порт, который был связан с этим процессом/PID.

Способ №4: через CurrPorts (стороннее ПО)

Есть несколько сторонних приложений, которые позволяют убить процесс, связанный с портом, одним щелчком мыши. Одним из них является CurrPorts, бесплатное программное обеспечение, которое выполняет работу в один миг.

Скачать: CurrPorts

По вышеупомянутой ссылке прокрутите вниз и нажмите «Загрузить CurrPorts». После загрузки файла извлеките его содержимое, а затем запустите файл cports.exe.

Главная страница CurrPorts предоставит вам всю информацию, связанную с данным процессом, включая его PID и используемый порт. Просто щелкните правой кнопкой мыши процесс, который вы хотите убить, и выберите «Убить процессы выбранных портов».

Теперь ваш порт свободен.

Хотя сторонних приложений предостаточно, командная строка и PowerShell по-прежнему являются одним из наиболее часто используемых методов для уничтожения процесса на порту, поскольку они помогают идентифицировать и выполнять процесс без каких-либо посторонних загрузок. Мы надеемся, что приведенные выше методы позволили вам завершить процессы на любом заданном порту в Windows 11.

  • How to open ftp on windows
  • How to install yarn on windows
  • How to run bash script on windows
  • How to recovery windows 10
  • How to open command line windows