Windows who uses 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

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 — пример использования

*

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

Успехов!

👋

How to Identify Programs Using or Blocking Ports on Your Computer

Windows:

The Netstat.exe utility has a switch that can display the process identifier (ID) associated with each connection to identify port conflicts. This information can be used to determine which process (program) listens on a given port.

Using Netstat command:

  1. Open a CMD prompt
  2. Type in the command: netstat -ano -p tcp
  3. You’ll get an output similar to this one
  4. Look out for the TCP port in the Local Address list and note the corresponding PID number

    Netstat-Command-Prompt-Displaying-TCP-Connections-and-Listening-Ports

Using Task Manager, you can match the process ID listed to a process name (program). This feature enables you to find the specific port that a program currently uses. Because this specific port is already in use by a program, another program is prevented from using that same port.

To Match the Process ID to a Program Using Task Manager:

  1. Press CTRL+ALT+DELETE, and then click Task Manager.
  2. Click the Processes tab.
  3. If you do not have a PID column, click View, click Select Columns, and then click to select the PID (Process Identifier) check box.
  4. Click the column header labeled «PID» to sort the process by their PIDs. You should be able to quickly find the process ID and match it to the program listed in Task Manager. 

To Match the Process ID to a Program Using the Command Line:

Example to find which process uses TCP port 9443:

C:\>netstat -ano -p tcp |find «9443»

Netstat-Command-Filtering-Port-443-Connections-Windows-Command-Prompt

Process with PID 1400 is listening on TCP port 9443. Now, we can query the task list to find the process.

C:\>tasklist |find «1400»

Tasklist-Command-Finding-Process-ID-1400-Windows-Command-Prompt

Here is a typical situation where the EveryonePrint Web service uses TCP port 9443.

Linux:

The Netstat.exe command has a switch that can display the process identifier (PID) associated with each connection to identify port conflicts. This information can be used to determine which process (program) listens on a given port.

Using Netstat command:

  1. Open a terminal
  2. Type in the command: sudo netstat -ano -p tcp
  3. You’ll get an output similar to this one
  4. Look out for the TCP port in the Local Address list and note the corresponding PID number

    Netstat-Command-Display-Linux-Server-Listening-Ports-and-Java-Process

To Match the Process ID to a Program:

From the netstat list, you already know the Program name; you can have further details about it using the following command: 

ps -ef | grep <PID number>

Join the DZone community and get the full member experience.

Join For Free

Hello friends. In this tutorial, you will learn

  • How to check which process/application is using a particular port on Windows
  • How to check which port is being used by a particular process/application on Windows

How to Check Which Process/Application Is Using a Particular Port on Windows

Step 1 — Find the Process id of the Process Using the Given Port

Syntax

 netstat -aon | findstr<port_number>  

  • -a Displays all connections and listening ports.

  • -o Displays owning process Id associated with each connection.

  • -n Displays addresses and port numbers in numerical forms

On my system, it displays the following output. My Tomcat is up and running on port 8080 within Eclipse and I executed the following command.

 netstat -aon | findstr 8080 

Here the last column is telling the process id of the process which is using port 8080.

Explanation

netstat -aon

Will give you a list of process Ids which are using given port.

findstr 8080

findstr is functionally equivalent to grep command on Linux. From the output of netstat, findstr will give the lines which have word 8080 in it.

Step 2 — Find the Process/Application Name Using the Given Port Using the Process id Found in Step 1

Syntax

 tasklist | findstr <PID> 

This will give you the application name which is using that port.

On my system, I used the following command to check which process belongs to process id 9260.

 tasklist | findstr 9260 

Here, javaw.exe is the process which is using port 8080.

How to Check Which Port Is Being Used by a Particular Process/Application on Windows

Step 1 — Find the Process id of the Process Using a Process With the Given Name

Syntax

 tasklist | findstr <application_name/process_name>   

On my system, I executed the following command to find first process id of a process with name javaw.exe

 tasklist | findstr javaw.exe 

Here, 9260 is the process id of the process javaw.exe.

Step 2 — Find the Port Being Used by the Process id Found in Step 1

On my system, to find which port is being used by a process with process id 9260, I run

 netstat -aon | findstr 9260 

As you can see in the above output, process 9260 is using port 8080.

Use the Windows netstat command to identify which applications are using port 8080

  1. Hold down the Windows key and press the R key to open the Run dialog.
  2. Type “cmd” and click OK in the Run dialog.
  3. Verify the Command Prompt opens.
  4. Type “netstat -a -n -o | find «8080»». A list of processes using port 8080 is displayed. 
  • the symbol before the word «find» is the pipe symbol («|») and not a lower-case l.
  • the outer quotes should NOT be entered. Quotes around the port number are required.

If one or more processes make use of port 8080, then the processes are displayed. If no method accesses port 8080, then no information is restored.

Summary

In this tutorial, you learned

Use of the netstat command with -aon options together with the findstr command to find out which process is using a particular port, and vice versa.

Thanks for reading. Share it with someone you think it might help.

MS Windows
Tool

Opinions expressed by DZone contributors are their own.

Related

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

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии
  • Как установить на рабочий стол установить картинку на рабочий стол windows 7
  • Увеличить размер ярлыков на рабочем столе windows
  • Windows get cpu temperature
  • Редактор рисунков для windows
  • Icloud sync for windows