How to Find and Terminate Processes by Port Number on Windows and Linux

Occasionally, a network port on your system might remain occupied by a process even after the application seemingly closes or disconnects.

This situation frequently occurs with development servers that haven’t shut down cleanly or with orphaned processes like interrupted SSH tunnels. When a port is locked, other applications cannot use it, necessitating manual intervention.

This guide details common methods for identifying the process utilizing a specific port and terminating it on Windows and Linux operating systems using command-line tools.

Why Terminate a Process by Port?

The primary reason to terminate a process holding a port open is to release that port for use by another application. When a process terminates abnormally or fails to release its network resources, the port it was listening on can remain bound. This prevents new instances of the same application, or different applications needing that specific port, from starting successfully.

Read: Differences between a thread and a process

Solutions for Releasing Occupied Ports

The approach to freeing a port involves two main steps: identifying the Process Identifier (PID) associated with the port, and then using that PID to terminate the process.

Windows Solutions

Windows offers several command-line utilities for managing processes and network connections.

Using Command Prompt (`cmd.exe`)

  1. Find the Process ID (PID): Open Command Prompt (potentially requiring Administrator privileges). Execute the following command, replacing with the target port number:
    
    netstat -ano | findstr :
                

    Look for lines indicating a “LISTENING” state. The last number on such a line is the PID.

    Example Output (for port 8080):

    
      TCP    0.0.0.0:8080           0.0.0.0:0              LISTENING       18264
                

    Here, the PID is 18264.

  2. Terminate the Process: Use the PID found in the previous step with the taskkill command. The /F flag forcefully terminates the process.
    
    taskkill /PID  /F
                

    Example:

    
    taskkill /PID 18264 /F
                

Note: In some environments like Git Bash, you might need to use tskill instead of taskkill, or use double slashes for the flags, e.g., taskkill

Read: An introduction to Windows PowerShell for beginners

Using Windows PowerShell

PowerShell provides more integrated cmdlets for network and process management.

  1. Find PID using `netstat` (as above):
    
    netstat -ano | findstr :
                
  2. Terminate using `Stop-Process`:
    
    Stop-Process -Id  -Force
                

    Alternatively, combine finding and stopping into a single PowerShell command (works well in PowerShell v1+):

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

    Example for port 3000:

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

    Within Windows Terminal, the command kill often works as an alias for Stop-Process.

Using `npx kill-port` (Requires Node.js/npm)

If you have Node.js and npm (version 5.2.0 or higher) installed, the `npx` command provides a convenient cross-platform way to kill a process by port.


npx kill-port 
    

Example:


npx kill-port 8080
    

Note: This might require administrator privileges, and its effectiveness can sometimes vary depending on the process being terminated.

Read: Repeat Linux Commands Every X Seconds for Real-Time Monitoring, Automation & Precise Scheduling

Automated Scripts (.bat Files)

For frequently performed tasks, scripting can save time.

One-liner for Command Line (replace 8080):


for /f "tokens=5" %a in ('netstat -aon ^| find ":8080" ^| find "LISTENING"') do taskkill /f /pid %a
    

One-liner for inside a `.bat` file (replace 8080):


@ECHO OFF
for /f "tokens=5" %%a in ('netstat -aon ^| find ":8080" ^| find "LISTENING"') do taskkill /f /pid %%a
PAUSE
    

Interactive `.bat` script: Create a file named `killport.bat` with the following content:


@ECHO OFF
set /P port="Enter port : "
echo Showing process running with port %port%
netstat -ano | findstr ":%port%"
set /P pid="Enter PID to kill : "
taskkill /pid %pid% /f
set /P exit="Press any key to exit..."
    

Run this script, enter the port number when prompted, identify the PID from the output, and then enter the PID to terminate it.

Graphical User Interface (GUI) Tools

Tools like `CurrPorts` (a third-party utility) or the built-in Windows `Resource Monitor` (accessible via Task Manager) allow visual identification and termination of processes using specific network ports via their Network tabs.

Using Python (`psutil`)

If you prefer Python and have the `psutil` library installed, you can programmatically find and terminate the process:


from psutil import process_iter
from signal import SIGTERM # or SIGKILL

target_port = 8080 # Replace with your target port

for proc in process_iter():
    try:
        for conns in proc.connections(kind='inet'):
            if conns.laddr.port == target_port:
                print(f"Found process {proc.pid} using port {target_port}. Terminating.")
                proc.send_signal(SIGTERM) # or proc.send_signal(SIGKILL) for forceful kill
                # Use 'continue' if you want to kill all processes on the port
                # continue 
    except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess):
        pass
    

Read: How to Kill Processes in Linux: Beginner-Friendly Guide to Command Line Termination

Linux Solutions (Including Windows Subsystem for Linux – WSL)

Linux systems commonly use `lsof` or `netstat` combined with the `kill` command.

Using `lsof` and `kill`

The `lsof` (List Open Files) command can directly identify processes using a specific network port.

  1. Find the PID: Use the `-t` flag for terse output (PID only) and `-i` to specify the network interface (using `:`). Requires `sudo`.
    
    sudo lsof -t -i:
                

    Example for port 3000:

    
    sudo lsof -t -i:3000
                

    This command directly outputs the PID(s).

  2. Terminate the Process: Use the `kill` command. Sending signal `9` (SIGKILL) forcefully terminates the process.
    
    sudo kill 
    # or for forceful termination:
    sudo kill -9 
                

    You can combine these steps into a single command:

    
    # Sends SIGTERM (graceful shutdown)
    kill $(sudo lsof -t -i:)
    # Sends SIGKILL (forceful shutdown)
    kill -9 $(sudo lsof -t -i:)
                

Using `netstat` and `kill`

Alternatively, use `netstat` with appropriate flags (`-vanp tcp` can be effective) and filter using `grep`.

  1. Find the PID:
    
    sudo netstat -vanp tcp | grep 
                

    The output will typically show the PID associated with the listening process.

  2. Terminate the Process:
    
    sudo kill -9 
                

Verification

After attempting to terminate a process, you can verify if the port is now free by re-running the `netstat` or `lsof` command used initially to find the PID. If the command returns no results for the specific port in a “LISTENING” state, the process was likely terminated successfully and the port released.

Windows Example:


netstat -ano | findstr :
            

Linux Example:


sudo lsof -i:
    

Empty output or output showing no process in a LISTENING state indicates success.

Important Considerations

  • Administrator/Root Privileges: Most commands for finding PIDs across all users (`netstat -ano`, `sudo lsof`) and terminating arbitrary processes (`taskkill /F`, `sudo kill`) require elevated permissions (Run as Administrator on Windows, `sudo` on Linux).
  • Force Killing (`/F` or `-9`): Using forceful termination flags (like `/F` for `taskkill` or `-9` for `kill`) immediately stops the process without allowing it to save data or clean up resources. Use this cautiously, especially with critical applications or services. A standard `taskkill /PID ` or `kill ` (without `-9`) is generally preferred first, as it allows the process a chance to shut down gracefully (SIGTERM signal).
  • System Processes: You typically cannot (and should not) terminate critical system processes. For instance, attempting to kill PID 0 on Windows will result in an error.
  • Restarting Services: Some applications run as system services configured to restart automatically upon failure or termination. Killing such a process might only provide temporary relief, as the service manager may restart it immediately. Proper management involves stopping the service through the operating system’s service controls (e.g., `services.msc` on Windows, `systemctl` on Linux).
  • Tool Availability: Commands like `lsof` might not be installed by default on all Linux distributions and are generally not available on standard Windows (though they are common within WSL). Ensure the necessary tools are present on your system.

Conclusion

Freeing up an occupied network port is a common task for developers and system administrators. Whether on Windows or Linux, the process involves identifying the problematic process ID using tools like `netstat` or `lsof`, and then terminating that process using commands such as `taskkill`, `Stop-Process`, or `kill`. Understanding the available tools and the implications of forceful termination allows for effective resolution of port conflicts.

Frequently Asked Questions (FAQ)

Why do I need Administrator or `sudo` privileges?
Viewing processes belonging to other users or system services (`netstat -ano`, `sudo lsof`) and terminating arbitrary processes often requires elevated rights to prevent unauthorized interference with system operation.
What’s the difference between `taskkill` and `tskill` on Windows?
`taskkill` is the more modern and standard command for terminating processes on Windows. `tskill` is an older command, sometimes found useful within specific environments like older versions of Git Bash where `taskkill` might not behave as expected.
What is `npx kill-port` and does it always work?
`npx kill-port` is a command provided by a Node.js package (`kill-port`) that simplifies finding and killing a process by its port number. It requires Node.js/npm to be installed. While convenient, its effectiveness can sometimes depend on whether it’s run with sufficient privileges to terminate the target process.
What do the `/F` (Windows) and `-9` (Linux) flags mean?
Both flags signal a forceful termination. `/F` for `taskkill` and `-9` (SIGKILL) for `kill` instruct the operating system to stop the process immediately, without giving it a chance to shut down gracefully (like saving files). This should be used when a normal termination request is ignored but can lead to data loss or corruption.
Why can’t I kill PID 0 on Windows?
PID 0 typically represents the System Idle Process or other core system functions. It’s a critical part of the operating system kernel and cannot be terminated by user commands.
How can I automate killing a process on a specific port?
On Windows, you can use `.bat` scripts combining `netstat` and `taskkill` using `for /f` loops. On Linux, shell scripts using command substitution `$(…)` with `lsof` and `kill` are common. PowerShell also offers powerful scripting capabilities with `Get-NetTCPConnection` and `Stop-Process`.
The `lsof` command is not found?
`lsof` is a standard Linux utility but might not be installed by default on minimal systems. Use your distribution’s package manager to install it (e.g., `sudo apt install lsof` on Debian/Ubuntu, `sudo yum install lsof` on CentOS/RHEL). It is not a native Windows command but is available within WSL.
Why does the `kill` command work in Windows Terminal?
In modern Windows PowerShell (often the default in Windows Terminal), `kill` is typically set up as a default alias for the `Stop-Process` cmdlet. It’s not the same as the native Linux `kill` command but provides similar functionality for stopping processes by PID.

 


If you like the content, we would appreciate your support by buying us a coffee. Thank you so much for your visit and support.

 

Nikolaus Oosterhof

Nikolaus holds a degree in software development and has a strong passion for all things tech-related, especially gadgets with screens. Though he is nostalgic for older phone models, he's a retired gamer and continues to enjoy programming in open-source environments. Additionally, Nikolaus enjoys writing about Linux, macOS and Windows and has experience designing web pages.

Leave a Reply