Windows get process port

При запуске новых сервисов в 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

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:

Содержание статьи:

  • Типовые задачи и их решение
    • Вариант 1: смотрим список прослушиваемых портов + приложение (общий случай)
    • Вариант 2: а если наоборот — по названию приложения узнать порт
    • Вариант 3: исп-ем спец. приложения (более информативнее и быстрее)
  • Вопросы и ответы: 0

Доброго времени!

При запуске некоторого ПО/сервисов можно столкнуться с тем, что определенный порт в системе уже занят… какой-нибудь другой программой (скажем, настраиваете вы апач — и возникает конфликт порта 80. Например, на нем может «висеть/слушать» Skype…). Незадача…?

Собственно, в заметке приведу неск. способов, как можно относительно быстро узнать «кем» и «чем» заняты определенные порты — а это позволит быстро изменить их настройки и разрешить вопрос! (разумеется, приводить советы посмотреть описание установленного софта, в котором разработчики указывают порты — я не буду: ибо это долго, и не всегда продуктивно… 🙂).

*

Примечание:

  1. заметка носит информативный характер, и не явл. инструкцией в последней инстанции. Дело в том, что нередко встречаются не офиц. резервируемые порты… и, разумеется, точности здесь никакой быть не может;
  2. если у вас не получается подключиться к сетевым играм, есть проблемы с раздачей/загрузкой торрентов и пр. — ознакомьтесь с заметкой про проброс портов на роутере (это немного не по теме, но когда речь заходит об этом — очень часто приходится ссылаться на сию заметку).

*

Типовые задачи и их решение

Вариант 1: смотрим список прослушиваемых портов + приложение (общий случай)

По умолчанию в Windows есть консольная утилита netstat. Она позволяет посмотреть активные соединения протокола TCP/IP (в т.ч. там есть и порты).

*

Чтобы вывести полный список портов (TCP, UDP) нужно:

1) Запустить 📌командную строку от имени администратора.

2) Ввести команду Netstat –ao и нажать Enter.

(можно ее слегка изменить и использовать такую: netstat -aon| find «LISTENING»)

Примечание:

  • «-a» – см. все соединения и порты.
  • «-o» – см. числовые идентификаторы процесса, отвечающего за конкретное соединение (Process ID, сокращенно: PID).
  • «-n» – см. номера портов в числовом формате»;

img-Gde-tut-port-i-identifikator-sm.-skrin-ya-vyidelil.jpg

Где тут порт и идентификатор, см. скрин, я выделил // пример работы с командной строкой, команда netstat

📌 Для справки!

В списке, который предоставит нам команда Netstat, есть строки с аббревиатурами: «ESTABLISHED» и «LISTENING». В чем разница:

  • «ESTABLISHED» — означает, что в данный момент установлено соединение;
  • «LISTENING» — означает, что сокет ожидает соединения (в режиме прослушивания).

Причем, и тот и другой порты открыты, но один ожидает соединения, а другой уже установил соединение!

Например, протокол HTTP (это порт 80-й) находится в режиме прослушивания («LISTENING») до тех пор, пока кто-нибудь не зайдет на сервер. В тот момент, когда кто-нибудь будет загружать страницу — режим поменяется на «ESTABLISHED».

3) Например, понадобилось нам узнать какой процесс занял порт с идентификатором (PID) «5288» — вводим в командной строке tasklist | find «5288» и нажимаем Enter;

img-Vvodim-PID-i-smotrim-nazvanie-protsessa.jpg

Вводим PID и смотрим название процесса

4) Почти сразу же узнаем, что это фирменная утилита от производителя ноутбука ASUS (шла вместе с операционной системой Windows // инсталлируется автоматически при установке драйверов).

img-Asus.jpg

Asus

5) Кстати, если вам неудобно пользоваться командной строкой — то узнать название процесса и его расположение по PID можно в 📌диспетчере задач (Ctrl+Alt+Del): достаточно перейти во вкладку «Подробности».👇

img-Dispetcher-zadach-podrobnosti-sortirovka-po-ID-protsessu.jpg

Диспетчер задач — подробности — сортировка по ИД процессу

*

Вариант 2: а если наоборот — по названию приложения узнать порт

Относительно просто!

Находим нужный процесс в 📌диспетчере задач (вкладка «Подробности» для Windows 11). Узнаем его ИД (в моем случае 6216, взял для примера uTorrent).

img-uTorrent-ID-6216.jpg

uTorrent — ИД 6216

Далее в комодной строке набираем следующее:

netstat -aon| find «6216»

где вместо «6216» нужно указать свой ИД.

img-19411-port-ispolzuemyiy-uTorrent.jpg

19411 порт, используемый uTorrent

В результате определяем, что uTorrent слушает порт 19411

Кстати, в настройках uTorrent (если запустить саму программу) — можно тоже узнать и изменить этот порт на какой-нибудь другой.

img-Nastroyki-uTorrent-vyibor-porta.jpg

Настройки uTorrent — выбор порта

*

Вариант 3: исп-ем спец. приложения (более информативнее и быстрее)

📌 TCPView

Ссылка на сайт Microsoft: https://learn.microsoft.com/ru-ru/sysinternals/downloads/tcpview

TCPView — небольшая спец. утилита (не требующая установки), позволяющая очень быстро узнать список всех сетевых соединений, с информацией о портах, IP-адресах и пр.

Причем, список можно отсортировать по нужному вам столбцу + отфильтровать по какой-нибудь аббревиатуре. В общем, вещи удобная! См. скрин ниже. 👇

img-TCPView-spisok-prilozheniy-smotrim-vse-neobhodimyie-svoystva.jpg

TCPView — список приложений, смотрим все необходимые свойства

📌 CurrPorts

Ссылка на офиц. сайт: https://www.nirsoft.net/utils/cports.html#DownloadLinks

CurrPorts — еще одна сетевая утилита для просмотра сетевых подкл. В установке программа не нуждается, по информативности не уступает первой. Кстати, у утилиты есть рус. перевод (но скачать его нужно отдельно, есть на офиц. сайте).

img-CurrPorts-primer-ispolzovaniya.jpg

CurrPorts — пример использования

*

Дополнения по теме — приветствуются!

Успехов!

👋


3 minute read

Can’t use a specific port? Here’s how to check which port is in use in Windows with simple commands and apps like currports and tcpview.

This is top image

Windows has many applications connected or trying to connect to the internet at any point in time. With all those applications, it is only natural that they use many network ports.

Two or more applications may need the same port to work from time to time. When that specific port is already in use by one application, the other application cannot use that port, and it may show a warning message, error out, or crash entirely.

In those situations, it is better to know which ports are used and which application is using that specific port. That way, you can either change the port or terminate the problem-causing application so that the other one works as it should.

The good thing is that it is pretty easy to know which port is used by which application in Windows. So, without further ado, let me show the steps to find which ports are used in Windows 10 and 11 operating systems.

Note: The methods shown below work in Windows 7, 8, 10, and 11.

Command to check ports in

Using a single command, you can get a list of all the ports in use by various programs. This method is quite helpful if you want to take a quick glance at the ports in use.

  1. Search for “cmd” in the start menu, right-click on the Command Prompt and select “Run as Administrator.” This option lets you open the command prompt with admin rights.

    This is top image

  2. In the elevated command prompt window, execute the below command. You can copy and paste the command into the Command Prompt window by right-clicking inside it.
  3. You will see the port number right next to the IP address (ex: 192.168.42.198:50943) in the output result. You can see the highlighted portion of the attached image for better representation.

Keep in mind that the list will not be refreshed automatically. You have to execute the command again when you need an updated list. If you want the used port list to be updated automatically, follow one of the two methods illustrated below.

Use CurrPorts to find ports in use

Nirsoft Utilities has a pretty neat and lightweight tool called CurrPorts. It shows all the ports used by Windows and other programs. Let me show you how to use the application to get the information you need.

A quick note: In case you don’t know, Nirsoft has a lot of small and portable apps that are pretty useful in day-to-day life. If you’ve never used Nirsoft Utilities, browse the developer site and find many interesting little tools.

  1. First, download CurrPorts from the official website. Being a portable application, you don’t have to install it. After downloading, extract the exe file from the zip file and double-click the file to open it.

  2. As soon as you open the window, the application will list all the connections and their ports. You can find the port number under the Local Port section.

    This is CurrPorts image 1

  3. Being a dedicated port monitoring application, it offers quite a few options to manage the applications and ports. Right-click on any option, and you will see appropriate options like the ability to close the TCP connection, copying properties, application properties, etc.

    This is CurrPorts image 2

  4. If you want finer control, you can create your own filters to narrow down the search. To do that, select “Options -> Advanced Filters” option.

    This is CurrPorts image 3

Use Sysinternals TCPView to check ports in use

Sysinternals TCPView is a Microsoft tool that makes it easy to view all the TCP connections and ports used in Windows 10 and 11. The tool is very similar to CurrPorts.

  1. Download TCPView from the Sysinternals website, extract the exe file to your desktop, and double-click on it.

  2. As soon as you open the application, you will see a user agreement. Agree to the agreement, and you will instantly see all the TCP connections and ports in use. You will find the port numbers under the Local Port section.

    This is CurrPorts image 3

  3. You can end the connection and free the port if you want to. To do that, right-click on the connection and select “End Process.” This will terminates the process.

    This is CurrPorts image 3

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

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии
  • Можно ли установить linux вместе с windows 10
  • Бесшумный компьютер на windows
  • Как создать приложение на windows forms
  • Аналог ножниц в windows 10
  • Сброс сети windows 10 что делает