Find pid for port windows

Find Process ID of Process using given port in Windows
Once a while it happens that you try to start Tomcat and it complains “Port 8080 required by Tomcat v7.0 Server at localhost is already in use”. So that means there is already a process running in background that has occupied 8080 port. So how to identify the process in Windows task manager that is using port 8080? I am sure there must be a javaw.exe. But is there a better way to identify which process in windows is using a given port number? Yes…

How to Find Process ID of process that uses a Port in Windows

Our friend netstat will help us in identifying the process. netstat can list the running process and display information such as process id, port, etc. From this list we can filter the processes that has given port using findstr command.

List process by port number

netstat -ano | findstr 8080

Code language: Bash (bash)
find process id by port number windows

Output

Proto Local Address Foreign Address State PID TCP 0.0.0.0:8080 0.0.0.0:0 LISTENING 29848

Code language: Bash (bash)
  • -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.

We can use netstat to list all the processes.

List all processes by PID

netstat -ano

Code language: Bash (bash)

Kill the Process by PID

Once we identify the process PID, we can kill the process with taskkill command.

taskkill /F /PID 12345

Code language: Bash (bash)

Where /F specifies to forcefully terminate the process(es). Note that you may need an extra permission (run from admin) to kill some certain processes.

windows-task-manager-process-task-by-port-number

Or else you can use our old trusted Windows Task Manager to kill the process for given process id. If PID is not visible in your task manager then you can enable it by Right clicking on table header under Details tab, click Select Columns and then check PID.

How to Find the Process Which Uses the Port in Linux and Windows?

If you’ve faced a blocked or in-use port, it can be frustrating. Fortunately, there are easy ways for Windows and Linux users to find which program or process is using a port and resolve conflicts.

In this guide, we’ll walk you through how to find the program or process that’s using a particular port on both Windows and Linux systems, and I’ll also show you the tools available to resolve port conflicts.

Why Knowing Which Process Uses a Port is Important?

Ports are essential for network communication, and multiple programs might attempt to use the same port, leading to conflicts. By finding which process is using a specific port, you can avoid these conflicts, ensure smooth network operations, and troubleshoot issues that arise from port usage.

Method 1: Using Command Prompt (Windows)

The Netstat utility on Windows can help you find which application is using a specific port. Here’s how you can use this method to track down which process is occupying a particular port:

Press the Windows key, type CMD in the search box, right-click on Command Prompt, and select Run as Administrator. Then enter the command:

netstat -aon -p tcp

This command will display a list of all TCP connections, their local addresses, the process IDs (PIDs), and the state of each connection.

Look through the list for the port you’re concerned about (e.g., port 135 in the above screenshot).
Find the PID number associated with that port in the last column. i.e; 1436 there.

To match the PID with the program name, use the following command in the same Command Prompt window:

tasklist | find "PID_number"

For example, if the PID number from the previous command was 1400, you would run: tasklist | find “1436”

This will show you the name of the application using that port (e.g., FileZilla Server, SQL Server, etc.).

"tasklist | find "PID_number" command find the process which uses the port via Windows command prompt

Method 2: Using Resource Monitor (Windows)

If you prefer a more visual approach, Windows’ Resource Monitor tool can provide a detailed view of the programs using specific ports.

  1. Press the Windows key and type resource monitor or resmon in the search box. Click on Resource Monitor to open the tool.
  2. In Resource Monitor, navigate to the Network tab.

In the Listening Ports section, you’ll see a list of all open ports and the applications that are using them.
You can check the PID column to match the process IDs with the applications.

Use resource monitor application in windows to find out the program using the port

Method 3: Command Line on Linux

If you’re using Linux, the process is quite similar, but instead of Command Prompt, you’ll use the Terminal to run the necessary commands.

  1. Open a terminal on your Linux machine.
  2. Enter the following NetStat command to get a list of active connections:
sudo netstat -ano -p tcp

This will show all TCP connections with their corresponding PIDs.

command: "netstat -ano -p tcp" executed to find out the process using the port in Linux terminal.

Similar to Windows, locate the specific port number and note the associated PID.

Once you have the PID, you can use the following command to find more details about the process:

ps -ef | grep

This will display the program name and other details related to the process ID.

Additional Tips:

How to Interpret the netstat Command:

You can customize the netstat command with different flags to refine the results:

-a Displays all active connections and listening ports.
-n Shows addresses and port numbers in numerical form (instead of resolving them to hostnames).
-o Displays the PID associated with each connection.
-p Displays the protocol (TCP, UDP, etc.).
Task Manager PID Column:

If you’re using Windows Task Manager to match a PID, ensure the PID column is visible. To do this, click on the View menu, select Select Columns, and check the box for PID (Process Identifier).

Knowing which application is using a port is essential for troubleshooting network and application conflicts. By following the methods above, you can easily find which program or process is using a particular port on both Windows and Linux systems. Whether you prefer using the command line or a graphical interface, there are plenty of ways to resolve port conflicts efficiently.

Take Control with cPanel

Manage every aspect of your website with our intuitive cPanel. From email setup to file management, enjoy complete control. Experience reliable hosting with robust features.

Explore cPanel Plans

Related Blogs:

При запуске новых сервисов в Windows, вы можете обнаружить что нужный порт уже занят (слушается) другой программой (процессом). Разберемся, как определить какая программ прослушивает определенный TCP или UDP порт в Windows.

Например, вы не можете запустить сайт IIS на стандартном 80 порту в Windows, т.к. этот порт сейчас занят (при запуске нескольких сайтов в IIS вы можете запускать их на одном или на разных портах). Как найти службу или процесс, который занял этот порт и завершить его?

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

netstat -aon| find "LIST"

Или вы можете сразу указать искомый номер порта:

netstat -aon | findstr ":80" | findstr "LISTENING"

Используемые параметры команды netstat:

  • a – показывать сетевые подключения и открытые порты
  • o – выводить идентфикатор професса (PID) для каждого подключения
  • n – показывать адреса и номера портов в числовом форматер

По выводу данной команды вы можете определить, что 80 порт TCP прослушивается (статус
LISTENING
) процессом с PID 16124.

netstat найти программу, которая заняла порт

Вы можете определить исполняемый exe файл процесса с этим PID с помощью Task Manager или с помощью команды:

tasklist /FI "PID eq 16124"

Можно заменить все указанные выше команды одной:

for /f "tokens=5" %a in ('netstat -aon ^| findstr :80') do tasklist /FI "PID eq %a"

С помощью однострочной PowerShell команды можно сразу получить имя процесса, который прослушивает:

  • TCP порт:
    Get-Process -Id (Get-NetTCPConnection -LocalPort 80).OwningProcess
  • UDP порт:
    Get-Process -Id (Get-NetUDPEndpoint -LocalPort 53).OwningProcess

powershell найти процесс, который слушает TCP порт

Можно сразу завершить этот процесс, отправив результаты через pipe в командлет Stop-Process:

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

Проверьте, что порт 80 теперь свободен:

Test-NetConnection localhost -port 80

проверить что порт свободен

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

cd /

dir tiny.exe /s /p

Или можно для поиска файла использовать встроенную команду where :

where /R C:\ tiny

В нашем случае мы нашли, что исполняемый файл
tiny.exe
(легкий HTTP сервер), который слушает 80 порт, находится в каталоге c:\Temp\tinyweb\tinyweb-1-94

команда позволяет найти путь к exe файу в windows

Get PIDs using netstat and findstr replace <PORT> with the port you’re looking for.

netstat -aon | findstr /c:":<PORT>" /c:"PID"

Kill processes using taskkill replace <PROCESS_ID> with the PID from the previous command.

taskkill /F /PID <PROCESS_ID>

Example

If you need to kill the process running on port 3000, use this command to find the PID:

netstat -aon | findstr /c:":3000" /c:"PID"

Example output:

Proto  Local Address   Foreign Address   State       PID
TCP    0.0.0.0:3000    0.0.0.0:0         LISTENING   31448
TCP    [::]:3000       [::]:0            LISTENING   31448

The process ID (PID) is 31448, so use taskkill to end it. (The /F flag means force and is optional.)

taskkill /F /PID 31448

Explanation

Here’s a break down of how these commands work.

Step 1: Find PID of Processes on Port

netstat -aon | findstr /c:":<PORT>" /c:"PID"

netstat -aon

netstat command returns information about connections

-a Return all active connections

-o Include PID of each process

-n Don’t resolve hostnames. This makes it run MUCH faster.

We pipe the output of the netstat command to the findstr command which will filter out rows that don’t match our pattern/string.

findstr /c:":<PORT>" /c:"PID"

findstr returns lines from input that match provided strings / regex patterns.

Each /c:"<PATTERN>" is a string/regex pattern to match. If a row matches any of our patterns it will be shown.

/c:":<PORT>" Replace with the port you’re searching for.

/c:"PID" This is just so the header row of the netstat table will be shown. It’s optional.

Output should be a table of rows that match the port. Example:

Proto  Local Address          Foreign Address        State           PID
TCP    0.0.0.0:3000           0.0.0.0:0              LISTENING       31448
TCP    [::]:3000              [::]:0                 LISTENING       31448

The last column shows the Process ID (PID). We use that in the taskkill command to end the processes.

Step 2: Kill Processes by PID

taskkill /F /PID <PROCESS_ID>

Replace <PROCESS_ID> with the PID from the previous step.

Alternate Solution: Kill Processes by Program Name / Executable File

If you know the executable of the process you want to kill, you can use this command to end it.

Warning: This will end all of the processes run by that executable file. Don’t use this if there might be other processes you don’t want to kill that were started by the same executable.

taskkill /F /IM <EXECUTABLE_FILE or PROCESS_NAME>

Example to kill all NodeJS processes: taskkill /F /IM node.exe

In another article, we explained computer ports and what they’re used for. Other than that, what can we do with port information? Since all traffic in and out of the computer goes through ports, we can check on them to see what they’re doing. Maybe the port isn’t listening for traffic? Maybe something is using a port that shouldn’t be? 

We’re going to use the Windows command netstat to see our listening ports and PID (Process ID). We’re also going to see what we can do with that information.

What Is Netstat?

The netstat command is a combination of the words ‘network’ and ‘statistics’. The netstat command works in all versions of Windows from Windows XP right up to Windows 10. It’s also used in other operating systems (OS) like Unix and Linux, but we’ll stick to Windows here.

Netstat can provide us with:

  • The name of the protocol the port is using (TCP or UDP).
  • The local IP address and name of the computer and the port number being used.
  • The IP address and port number to which we’re connecting.
  • The state of a TCP connection. For details on what these states are, read the Event Processing section of RFC 793.
  • Use the key combination Win Key + X. In the menu that opens, select Command Prompt.
  • Enter the command <pre>netstat -a -n -o</pre>. The parameters for netstat are preceded with a hyphen, not a forward slash like many other commands. The -a tells it to show us all active connections and the ports on which the computer is listening.

    The -n tells netstat to show the IP addresses and ports as numbers only. We’re telling it to not try to resolve the names. This makes for a quicker and neater display. The -o tells netstat to include the PID. We’ll use the PID later to find out what process is using a specific port.

  • View the results and take note of the addresses, port numbers, state, and PID. Let’s say we want to know what’s using port 63240. Note that its PID is 8552 and it’s connecting to the IP address 172.217.12.138 on port 443.

What’s Using That Port?

  • Open Task Manager. That’s most easily done by using the key combination Ctrl + Shift + Esc.

  • Click on the Details tab. To make this easier to find, click on the PID column header to sort the PIDs numerically.

  • Scroll down to PID 8552 and see what process it is. In this case, it’s googledrivesync.exe. But is it really? Sometimes viruses can make themselves look like legitimate processes.

  • In a web browser, go to ipinfo.io. Enter the IP address 172.217.12.138. As we can see, the IP address is registered to Google. So this googledrivesync.exe is a legitimate one.

How To Get Port, PID, & Process Name In PowerShell

PowerShell is Microsoft’s newer way to use a command-line interface with Windows. We say newer, but it’s been around for several versions. You should learn PowerShell even if you’re a home user.

Most Windows commands also work in PowerShell, plus we can combine them with PowerShell’s cmdlets – pronounced command-lets. Joe at Winteltools.com provides the script for this method.

  • Open Notepad and enter the following code:
$netstat = netstat -aon | Select-String -pattern "(TCP|UDP)"
$processList = Get-Process

foreach ($result in $netstat) {
   $splitArray = $result -split " "
   $procID = $splitArray[$splitArray.length – 1]
   $processName = $processList | Where-Object {$_.id -eq $procID} |    select processname
   $splitArray[$splitArray.length – 1] = $procID + " " +      $processName.processname
   $splitArray -join " "
}

  • Save the file as get-NetstatProcessName.ps1. Make sure to note where it’s being saved. It’s important to change the Save as type: to All Files (*.*) or it will get saved as get-NetstatProcessName.ps1.txt and it won’t work for us.

  • Open PowerShell and navigate to the location in which the script was saved. In this case, it’s <pre>cd C:\Scripts</pre>. Hit Enter to run the command.

  • Run the script using dot-sourcing to make it work. That means use ./ before the name of the file. The command will be <pre>./get-NetstatProcessName.ps1</pre> 

  • Now we can see all the traditional netstat info plus the process name. No need to open Task Manager anymore.

Go Get Them

We’ve covered two ways to use the netstat command to see listening ports. It can be used either in the old Command Prompt or within a PowerShell script. With the information it can give us, we’ve looked at how it can help us figure out what our computer is doing. 

If you thought netstat is a great utility, take a look at some other Windows TCP/IP utilities like tracert, ipconfig, and nslookup. Or use Resource Monitor to get a better look into hidden website and Internet connections. There is a lot you can do to see exactly what your computer is doing.

Have you used netstat to solve a problem? Please tell us what you did. Any questions about how to use netstat? Please ask us in the comments below.

Related Posts

  • How to Fix a “This file does not have an app associated with it” Error on Windows
  • How to Fix an Update Error 0x800705b4 on Windows
  • How to Resolve “A JavaScript error occured in the main process” Error on Windows
  • How to Fix the Network Discovery Is Turned Off Error on Windows
  • How to Change Folder Icons in Windows

Ready for the best newsletter in tech?

Get daily tips, tricks, guides, and special offers delivered right to your inbox.

Понравилась статья? Поделить с друзьями:
0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии
  • Заверить подлинность microsoft windows
  • Висит окно подготовка windows
  • Карантин антивируса где находится windows 10
  • Заставка windows 10 pro
  • Lenovo g565 установка windows с флешки