При запуске новых сервисов в 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 — пример использования
*
Дополнения по теме — приветствуются!
Успехов!
👋
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.
В Windows при запуске сервисов может возникнуть конфликт портов, если нужный порт уже занят другим процессом. Например, IIS не запустится на порту 80, если он используется. В этой статье расскажем, как определить, какая программа прослушивает TCP или UDP порт, с помощью netstat, PowerShell, tasklist и как освободить порт.
Приобрести оригинальные ключи активации Windows 11 можно у нас в каталоге от 1690 ₽
Поиск программы по порту с помощью netstat
1. Выведите все прослушиваемые порты:
netstat -aon | find "LIST"
Параметры:
– -a: показывает все подключения и порты.
– -o: отображает PID процесса.
– -n: числовой формат адресов и портов.
2. Найдите процесс по конкретному порту (например, 80):
netstat -aon | findstr ":80" | findstr "LISTENING"
Пример вывода: порт 80 занят процессом с PID 16124.
3. Определите программу по PID:
tasklist /FI "PID eq 16124"
Вывод покажет имя исполняемого файла (например, tiny.exe).
4. Однострочная команда:
for /f "tokens=5" %a in ('netstat -aon ^| findstr :80') do tasklist /FI "PID eq %a"
Поиск программы с помощью PowerShell
1. Найдите процесс для TCP-порта:
Get-Process -Id (Get-NetTCPConnection -LocalPort 80).OwningProcess
2. Найдите процесс для UDP-порта:
Get-Process -Id (Get-NetUDPEndpoint -LocalPort 53).OwningProcess
3. Завершите процесс:
Get-Process -Id (Get-NetTCPConnection -LocalPort 80).OwningProcess | Stop-Process
4. Проверьте, свободен ли порт:
Test-NetConnection localhost -Port 80
Поиск пути к исполняемому файлу
1. Поиск файла по имени:
cd \
dir tiny.exe /s /p
2. Использование where:
where /R C:\ tiny
Пример: найдено c:\Temp\tinyweb\tinyweb-1-94\tiny.exe.
Устранение неполадок
Порт не отображается:
– Убедитесь, что процесс запущен (netstat -aon).
– Проверьте права администратора для PowerShell.
Конфликт портов:
– Завершите процесс (Stop-Process) или измените порт сервиса (например, в настройках IIS).
Файл не найден:
– Проверьте правильность имени файла в tasklist.
– Используйте where для поиска по всему диску.
Рекомендации
– Безопасность: Завершайте только известные процессы, чтобы не нарушить работу системы.
– Мониторинг: Используйте Resource Monitor (resmon) для визуального анализа сетевых подключений.
– Автоматизация: Создайте скрипт для проверки портов:
$port = 80
$process = Get-Process -Id (Get-NetTCPConnection -LocalPort $port -ErrorAction SilentlyContinue).OwningProcess
if ($process) { Write-Output "Port $port used by $($process.ProcessName) (PID: $($process.Id))" } else { Write-Output "Port $port is free" }
– Логи: Проверяйте Event Viewer (eventvwr) для анализа ошибок портов.
Определение программы, использующей порт в Windows, возможно через netstat, tasklist или PowerShell (Get-NetTCPConnection, Get-NetUDPEndpoint). Эти инструменты позволяют быстро найти процесс, завершить его или освободить порт. Использование PowerShell упрощает автоматизацию и предоставляет гибкость для анализа сетевых подключений.
Лицензионный ключ активации Windows от
Open ports in Windows 10 are often deemed dangerous because hackers can exploit them if the service or application the ports are associated with are unpatched or lack basic security protocols. Therefore, it is recommended to close any listening network ports that your system isn’t using.
Let us brief you on what ports are and why they can be dangerous.
Table of Contents
What are network ports?
Network ports are used by Windows services and applications to send and receive data over the network. If you wonder if this is what the IP address is used for, then you are absolutely correct. However, a unique IP address defines the path to a specific device, whereas a port defines what application or service on that particular device to send that information to.
Just like the IP addresses, a port is also unique within its ecosystem. Meaning, the same port cannot be used by two different services/applications. Therefore, both of these unique identifiers, the IP address, and the port number, are used to send and receive information from a computer.
A port number can be found suffixed to an IP address, as in the example below:
xxx.xxx.xxx.xxx:80
Here, the numbers followed by the colon denote the port number. Below are a few ports used by certain services and applications by default:
- FTP – 21
- SSH – 22
- Telnet – 23
- SMTP – 25
- DNS – 53
- DHCP – 67 & 68
- HTTP – 80 & 8080
- HTTPS – 443
- SNMP – 161
- RDP – 3389
A single IP address can have 65535 TCP and 65535 UDP ports in total.
Are open network ports dangerous?
Not all ports that are listening are dangerous. Sometimes an application opens the ports automatically without informing the users. If the application is poorly constructed and the security protocols lack the basic infrastructure, an attacker might exploit those and infiltrate your PC.
An open networking port is not always dangerous, but it is always better to keep your guard up and close any ports that are not required.
2 ways to check which ports are open/listening in Windows 10
You can figure out which ports are currently open on your computer, even if the installed applications did not inform you that they are using them. Here are 2 ways to check which ports are open and which service/application uses them on your local computer before you proceed to block them.
Here is a guide to check if a remote network port is open.
Determine open ports with process name using Command Prompt
Some applications give out the name of the application/service associated with a port number. You can use the below-given command in Command Prompt to determine which ports are open and what are the names of the associated applications.
- Open Command Prompt with administrative privileges.
- Enter the following command:
netstat -ab
- Command Prompt will now display the output of open network ports with their associated application/service names, as in the image below:
Since the IP address assigned to our computer is 10.0.0.31, it displays different ports used by various applications suffixed to the IP address. However, as you may notice, some of the names of the services and applications are unidentifiable. For that, we shall adopt the second method.
Determine open ports with process ID using Command Prompt
In this approach, we shall be comparing the process IDs of the running applications and services associated with the ports and then determining the name of the process using the Task Manager. Here is how to do so:
- Open Command Prompt with administrative privileges.
- Enter the following command:
netstat -aon
- Command Prompt will now display a list of TCP and UDP ports currently listening on your computer. Note the associated PIDs to compare from the Task Manager.
- Now open the Task Manager by right-clicking on the Taskbar and clicking on Task Manager. Or, you may use the Ctrl + Shift + Esc shortcut keys.
- Now switch to the Details tab within the Task Manager and match the PID with the associated name of the process/application.
Now you have sufficient information on the ports you would like to close, if any. Proceed to the next step to block/close any listening ports on your computer.
How to close an open port
If you have found a port that you are no longer using or are not sure if it is secure to keep open, you should preferably block it. If you wish to close an open port, you can do so with Windows Firewall or Windows Defender in case of Windows 10.
- Open the Windows Firewall by going to Start –> Control Panel –> Windows Firewall. If you are using Windows 10, you can open the Windows Defender Firewall by going to Run –> firewall.cpl.
- From the left side menu, click on Advanced settings.
- From the right side menu of the new window, select Inbound Rules.
- Then click New rule in the right pane.
- On the Rule type screen in New inbound rule wizard, select Port and then click Next.
- On the next screen, select the type of port as determined through the Command Prompt earlier, and then enter the port number you want to close in front of Specific local ports. Click Next when done.
- On the next screen, select Block the connection and then click Next.
- On the Profile screen, select All Profiles and click Next.
- Now set a name for the rule and click Finish.
You have now successfully disabled the port. You can repeat the steps to block additional ports or delete this one by navigating to the Inbound rules and removing the respective rules.
How to quickly close ports using Command Prompt
A couple of commands can be used to identify the processes that have opened the ports and then close the ports by killing the process.
- Open Command Prompt and run the command: netstat -a -o -n. This will show all the open ports in your system along with their current state and the process ID that have opened the ports.
- If you want to find a specific port, you should run the command: netstat -a -o -n | findstr “993”. Replace 993 with the port number you want to find.
- The last column on the list is the Process ID or PID number. Killing the process will automatically close the listening port. To kill the process, run the command: taskkill /pid 993.
Please note that this is a quick and temporary way of closing the port using the command prompt. If you want to permanently block the port from opening again, you should follow the first method given above.
How to block network ports in Windows Firewall using Command Prompt
Block port in Windows Firewall using command line
You can also permanently block ports in Windows Defender Firewall using the Command Prompt.
To create a block port rule in Windows Firewall, run the following command in Command Prompt:
netsh advfirewall firewall add rule name="Rule Name" protocol=TCP dir=out remoteport=993 action=block
Replace Rule Name with your own rule name, for example, since I’m blocking IMAP port, I’ll name the rule as Block IMAP. Replace TCP with either RCP or UDP, whichever port you want to block. Replace 993 with the actual port number you want to block.
Unblock/Open port in Windows Firewall using command line
To open the port again, simply run the following command in CMD:
netsh advfirewall firewall delete rule name="Rule Name"
Replace Rule Name with the actual rule name, Block IMAP in my case. This will delete the rule that we created above.
Closing words
Listening ports are not always dangerous, as it is very much dependent on what application/service it is open through. Nonetheless, it is still important not to give the attacker any chance to exploit your system’s vulnerabilities and wise to close any ports that are not being used.