При запуске новых сервисов в 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.
Вы можете определить исполняемый 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
Можно сразу завершить этот процесс, отправив результаты через 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
Содержание статьи:
- Типовые задачи и их решение
- Вариант 1: смотрим список прослушиваемых портов + приложение (общий случай)
- Вариант 2: а если наоборот — по названию приложения узнать порт
- Вариант 3: исп-ем спец. приложения (более информативнее и быстрее)
- Вопросы и ответы: 0
Доброго времени!
При запуске некоторого ПО/сервисов можно столкнуться с тем, что определенный порт в системе уже занят… какой-нибудь другой программой (скажем, настраиваете вы апач — и возникает конфликт порта 80. Например, на нем может «висеть/слушать» Skype…). Незадача…?
Собственно, в заметке приведу неск. способов, как можно относительно быстро узнать «кем» и «чем» заняты определенные порты — а это позволит быстро изменить их настройки и разрешить вопрос! (разумеется, приводить советы посмотреть описание установленного софта, в котором разработчики указывают порты — я не буду: ибо это долго, и не всегда продуктивно… 🙂).
*
Примечание:
- заметка носит информативный характер, и не явл. инструкцией в последней инстанции. Дело в том, что нередко встречаются не офиц. резервируемые порты… и, разумеется, точности здесь никакой быть не может;
- если у вас не получается подключиться к сетевым играм, есть проблемы с раздачей/загрузкой торрентов и пр. — ознакомьтесь с заметкой про проброс портов на роутере (это немного не по теме, но когда речь заходит об этом — очень часто приходится ссылаться на сию заметку).
*
Типовые задачи и их решение
Вариант 1: смотрим список прослушиваемых портов + приложение (общий случай)
По умолчанию в Windows есть консольная утилита netstat. Она позволяет посмотреть активные соединения протокола TCP/IP (в т.ч. там есть и порты).
*
Чтобы вывести полный список портов (TCP, UDP) нужно:
1) Запустить 📌командную строку от имени администратора.
2) Ввести команду Netstat –ao и нажать Enter.
(можно ее слегка изменить и использовать такую: netstat -aon| find «LISTENING»)
Примечание:
- «-a» – см. все соединения и порты.
- «-o» – см. числовые идентификаторы процесса, отвечающего за конкретное соединение (Process ID, сокращенно: PID).
- «-n» – см. номера портов в числовом формате»;
Где тут порт и идентификатор, см. скрин, я выделил // пример работы с командной строкой, команда netstat
📌 Для справки!
В списке, который предоставит нам команда Netstat, есть строки с аббревиатурами: «ESTABLISHED» и «LISTENING». В чем разница:
- «ESTABLISHED» — означает, что в данный момент установлено соединение;
- «LISTENING» — означает, что сокет ожидает соединения (в режиме прослушивания).
Причем, и тот и другой порты открыты, но один ожидает соединения, а другой уже установил соединение!
Например, протокол HTTP (это порт 80-й) находится в режиме прослушивания («LISTENING») до тех пор, пока кто-нибудь не зайдет на сервер. В тот момент, когда кто-нибудь будет загружать страницу — режим поменяется на «ESTABLISHED».
3) Например, понадобилось нам узнать какой процесс занял порт с идентификатором (PID) «5288» — вводим в командной строке tasklist | find «5288» и нажимаем Enter;
Вводим PID и смотрим название процесса
4) Почти сразу же узнаем, что это фирменная утилита от производителя ноутбука ASUS (шла вместе с операционной системой Windows // инсталлируется автоматически при установке драйверов).
Asus
5) Кстати, если вам неудобно пользоваться командной строкой — то узнать название процесса и его расположение по PID можно в 📌диспетчере задач (Ctrl+Alt+Del): достаточно перейти во вкладку «Подробности».👇
Диспетчер задач — подробности — сортировка по ИД процессу
*
Вариант 2: а если наоборот — по названию приложения узнать порт
Относительно просто!
Находим нужный процесс в 📌диспетчере задач (вкладка «Подробности» для Windows 11). Узнаем его ИД (в моем случае 6216, взял для примера uTorrent).
uTorrent — ИД 6216
Далее в комодной строке набираем следующее:
netstat -aon| find «6216»
где вместо «6216» нужно указать свой ИД.
19411 порт, используемый uTorrent
В результате определяем, что uTorrent слушает порт 19411…
Кстати, в настройках uTorrent (если запустить саму программу) — можно тоже узнать и изменить этот порт на какой-нибудь другой.
Настройки uTorrent — выбор порта
*
Вариант 3: исп-ем спец. приложения (более информативнее и быстрее)
📌 TCPView
Ссылка на сайт Microsoft: https://learn.microsoft.com/ru-ru/sysinternals/downloads/tcpview
TCPView — небольшая спец. утилита (не требующая установки), позволяющая очень быстро узнать список всех сетевых соединений, с информацией о портах, IP-адресах и пр.
Причем, список можно отсортировать по нужному вам столбцу + отфильтровать по какой-нибудь аббревиатуре. В общем, вещи удобная! См. скрин ниже. 👇
TCPView — список приложений, смотрим все необходимые свойства
📌 CurrPorts
Ссылка на офиц. сайт: https://www.nirsoft.net/utils/cports.html#DownloadLinks
CurrPorts — еще одна сетевая утилита для просмотра сетевых подкл. В установке программа не нуждается, по информативности не уступает первой. Кстати, у утилиты есть рус. перевод (но скачать его нужно отдельно, есть на офиц. сайте).
CurrPorts — пример использования
*
Дополнения по теме — приветствуются!
Успехов!
👋
Существуют разные способы решения этой задачи. Мы расскажем о двух: с помощью командной строки и Диспетчера задач (Task Manager) либо с использованием прекрасного бесплатного приложения с полным набором нужных функций.
Способ 1: командная строка и Диспетчер задач
Для начала нужно с помощью командной строки узнать, какие порты используются в данный момент. При этом для каждого порта указывается идентификатор процесса, которым он занят. С помощью этого идентификатора можно затем выяснить, что за приложение использует нужный порт.
Откройте командную строку (желательно от имени администратора, чтобы увидеть все процессы) и введите следующую команду:
netstat -aon | more
Справа показаны PID – идентификаторы процессов (на скриншоте ниже они выделены белым). Найдите нужный вам порт и посмотрите, с каким идентификатором он связан. Например, на нашем скриншоте адрес 0.0.0.0:80, т. е. порт 80, связан с процессом 4708.
Теперь просто откройте Диспетчер задач и найдите в списке нужный ИД процесса. Возможно, для этого придется использовать опцию «Отображать процессы всех пользователей» (Show Processes for All Users). Определив нужный процесс, можно его завершить (End Process), открыть расположение файла (Open File Location) или перейти к службам (Go to Service(s)).
Способ 2: утилита CurrPorts
Если вы не любитель командной строки и предпочли бы выяснить всю нужную информацию с помощью одной программы, рекомендуем прекрасную бесплатную утилиту CurrPorts от NirSoft – одного из наших любимых разработчиков свободного ПО.
Просто запустите программу – и увидите все необходимые данные: процессы с полными адресами соответствующих файлов, занятые ими локальные и удаленные порты.
Можно дважды щелкнуть на любом пункте, чтобы посмотреть подробные сведения.
С помощью CurrPorts также можно завершить процесс, не заглядывая ради этого в Диспетчер задач.
Скачать CurrPorts можно с сайта nirsoft.net.
Автор: Lowell Heddings
Перевод
SVET
Оцените статью: Голосов
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
- Hold down the Windows key and press the R key to open the Run dialog.
- Type “cmd” and click OK in the Run dialog.
- Verify the Command Prompt opens.
- 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
A Port basically serves as an interface between your computer and the internet or other computers in the network. Every communication over the web is exchanged using these ports, so they are an essential part of the entire internet communication model.
Every IP address has a total of 65,535 ports, and it’s either a UDP port or a TCP port. An open port in a computer refers to a port that is configured to accept the connections, and a port that rejects connections is obviously a closed port.
While open ports are necessary for internet communication, they can be dangerous if the service listening on the port has bad security rules and is misconfigured. Such open ports are vulnerable to attacks.
In this post today, we will learn how to check which ports are being used in your machine, how to test if a Firewall is blocking a Port, and also learn how to check which process or service is using the open port.
Open Command Prompt, type the following, and hit Enter to view the Ports used along with the Process Identifiers (PIDs):
netstat -ano
This will display the ports on your PC. It will display the details in 5 columns-
- Protocols,
- Local Address,
- Foreign Address,
- State, and
- PID (Process Identifier).
The port numbers here are displayed under the Local Adress column, for example, if the Local Adress is 0.0.0.0:5040, 5040 here is the port number.
Under the State tab, you can check whether a port is open or not.
- LISTENING means that it just waits and it is ready to send an answer whenever a client program requests it. The connection becomes open when a client connects to that port and a conversation begins.
- ESTABLISHED means that the connection has been established.
- TIME_WAIT means it’s waiting for a reply or connection. this often happens when a port is activated and the connection has not yet. been established
- CLOSE_WAIT means that the other side of the connection has closed the connection.
This is how you check what all ports are open in your Windows 10.
You can also view the Ports used along with the Process Names by running this command:
netstat -ab
Read: How to use Port Query Tool (PortQry.exe).
Check which process or service is using the open port
Now when we know what all ports are open in our system, we can also check which service is using which open port. To check that, go to the PID (Process ID) tab.
Let’s take the example of our first open port in the list, port 135, and its PID is 1192.
Now open the Task Manager by hitting Ctrl+Alt+Delete. Go to the Services tab and check for PID 1192.
Under the Description tab, you will see which app/program uses that port. End that particular task if you want to close that connection.
Alternatively, you can also find this using this command:
takslist|findstr "1192"
This will display the program using the selected port.
If you are looking for an easy way, you can also use some third-party software to check what all ports are open in your Windows 10. There is quite a few such freeware available on the web which tell what all websites your computer is connecting to and what all ports are open in your PC. One of such freeware is CurrPorts.
Read: How to Block or Open a Port in Windows Firewall.
How to test if Firewall is blocking a Port
CurrPorts is a simple and portable freeware to check open ports that comes in a zip file and takes no time to download on your PC. Since it is portable software, you do not need to install it. Simply download it, extract all the files and run it. Make sure you download the correct version as per your machine’s configuration.
CurrPorts is a network monitoring software that displays the entire list of all open ports of your PC. Apart from the port number and its State, the freeware also shows detailed information about the processes using the open ports, the complete path of the process, file description, product name, file version, date and time it was created, and much more.
Once you download CurrPorts and run it, the main overview has it all. It displays the entire thing in one single window. You can check all the currently opened TCP and UDP ports and the program using that particular port in a single window. Check the screenshot below. You can select one or more processes at a time, check their ports and kill them if they seem to be unwanted. It also allows you to save the port information to an HTML/XML/Text file.
Furthermore, CurrPorts also lets you kill the process from the same window. Simply select the processes you want to kill, right-click and select ‘Kill processes of selected ports’ from the dropdown menu.
Another benefit of using CurrPorts is that it marks the suspicious TCP/UDP ports owned by the unidentified applications. So you can directly kill them and save your PC from a possible attack.
Certainly, using this freeware is an easier option as compared to the Command Prompt option mentioned above. You can download the software from the official website Nirsoft.net. Please note that there is a separate download link for x64 versions of Windows. This utility works fine with almost every version of Windows. It is a standalone executable utility so it doesn’t require any installation.
Read: Closed Port vs Stealth Port.