- How to Check for Ports in Use in Windows 10
- Use Nirsoft CurrPorts
- Command Prompt Method
- TCPView
- Устранение проблем нехватки портов Troubleshoot port exhaustion issues
- Динамический диапазон порта по умолчанию для TCP/IP Default dynamic port range for TCP/IP
- Устранение неполадок в истощении порта Troubleshoot Port exhaustion
- Метод 1 Method 1
- Метод 2 Method 2
- Метод 3 Method 3
- Полезные ссылки Useful links
How to Check for Ports in Use in Windows 10
At any one time, there’s a whole bunch of information being sent between your Windows 10 PC and the endless void of the Internet. This is done using a process whereby network-dependent processes seek out TCP and UDP ports, which they use to communicate with the Internet. First, your data gets sent to remote ports at the destination or website your processes are trying to connect to, then it gets received at local ports back on your PC.
Most of the time, Windows 10 knows how to manage ports and ensure that traffic is being directed through the right ports so that those processes can connect with what they need to. But sometimes two processes may be assigned to one port, or maybe you just want to get a better picture of your network traffic and what’s going in and out.
That’s why wrote this guide that shows you how to get an overview of your ports and see which applications are using which ports.
Use Nirsoft CurrPorts
NirSoft is one of the best indie software developers, giving us great utilities, like PassView and WirelessKeyView. While some people will prefer checking their ports without installing third-party software (in which case, scroll down to the CMD method), CurrPorts is easily the fastest and most convenient way to view your ports.
Once you’ve installed CurrPorts, just open it to see a list of all your ports currently in use. If you’re looking for local ports in use, just click the “Local Port” column at the top to order the list by port number (handy if you’re looking for a specific one). You can do the same thing with remote ports, too.
If you want to really find specific ports, click the “Advanced Filters” icon at the top and enter your string in the format they suggest. It should look something like the below image.
Hit OK when you’re ready, and the list will filter down to your queries.
Command Prompt Method
The integrated – though not necessarily the simplest – way to check open ports is to use the trusty command prompt.
Click the Start button, type cmd , then right-click “Command Prompt” when it shows up in the search results. Click “Run as administrator.”
Once you’re in the elevated command prompt, enter the following command:
This will steadily bring up a list of ports that is probably quite long, along with the Windows processes that are using them. (You can press Ctrl + A , then Ctrl + C to copy all information to the clipboard.) On the average PC, there will be two main local IP addresses that contain ports on your PC.
The first, in our case, is “127.0.0.1.” This IP address is otherwise known as “localhost” or a “loopback address,” and any process listening to ports here is communicating internally on your local network without using any network interface. The actual port is the number you see after the colon. (See image below.)
The bulk of your processes will probably be listening to ports prefixed with “192.168.xxx.xxx,” which is your IP address. This means the processes you see listed here are listening for communications from remote Internet locations (such as websites). Again, the port number is the number after the colon.
TCPView
If you don’t mind installing a third-party app and want to have more control over what’s going on with all your ports, you can use a lightweight app called TCPView. This immediately brings up a list of processes and their associated ports.
What make this better than the command prompt is that you can actively see the ports opening, closing and sending packets. Just look for the green, red and yellow highlights. You can also reorder the list by clicking the column headings, making it easier to find the process you want or two separate processes vying for the same port.
If you do find a process or connection you want to close, just right-click that process. You can then select “End process,” which is exactly the same function as the one in Windows task manager. Or you can click “Close Connection” to leave the process open but stop it from listening on a given port.
If you’re having some trouble in Windows 10, then see whether a Windows update may be causing it. We also have a handy guide for managing the health of your hard drive in Windows 10.
Related:
Content Manager at Make Tech Easier. Enjoys Android, Windows, and tinkering with retro console emulation to breaking point.
Устранение проблем нехватки портов Troubleshoot port exhaustion issues
Протоколы TCP и UDP работают на основе номеров портов, используемых для установления подключения. TCP and UDP protocols work based on port numbers used for establishing connection. Любому приложению или службе, необходимой для установления подключения TCP/UDP, потребуется порт на его стороне. Any application or a service that needs to establish a TCP/UDP connection will require a port on its side.
Существует два типа портов: There are two types of ports:
- Эфемерныепорты, которые обычно являются динамическими портами, являются набором портов, которые по умолчанию будут иметь каждый компьютер, чтобы сделать исходящие подключения. Ephemeral ports, which are usually dynamic ports, are the set of ports that every machine by default will have them to make an outbound connection.
- Известные порты — это определенный порт для конкретного приложения или службы. Well-known ports are the defined port for a particular application or service. Например, служба файловой серверной службы находится в порту 445, HTTPS — 443, HTTP — 80, RPC — 135. For example, file server service is on port 445, HTTPS is 443, HTTP is 80, and RPC is 135. Настраиваемые приложения также будут иметь определенные номера портов. Custom application will also have their defined port numbers.
Клиенты при подключении к приложению или службе будут использовать эфемерный порт из его машины для подключения к известному порту, определенному для этого приложения или службы. Clients when connecting to an application or service will make use of an ephemeral port from its machine to connect to a well-known port defined for that application or service. Браузер на клиентской машине будет использовать эфемерный порт для подключения к https://www.microsoft.com порту 443. A browser on a client machine will use an ephemeral port to connect to https://www.microsoft.com on port 443.
В сценарии, в котором один и тот же браузер создает много подключений к нескольким веб-сайтам, для любого нового подключения, которое пытается использовать браузер, используется эфемерный порт. In a scenario where the same browser is creating a lot of connections to multiple website, for any new connection that the browser is attempting, an ephemeral port is used. Через некоторое время вы заметите, что подключения начнут сбой и одна высокая возможность для этого будет потому, что браузер использовал все доступные порты для подключения за пределами и любые новые попытки установить подключение не удастся, так как нет более доступных портов. After some time, you will notice that the connections will start to fail and one high possibility for this would be because the browser has used all the available ports to make connections outside and any new attempt to establish a connection will fail as there are no more ports available. Когда все порты на компьютере используются, мы используем его как истощение порта. When all the ports are on a machine are used, we term it as port exhaustion.
Динамический диапазон порта по умолчанию для TCP/IP Default dynamic port range for TCP/IP
Чтобы соответствовать рекомендациям управления номерами, заданными в Интернете, Корпорация Майкрософт увеличила динамический диапазон клиентских портов для исходяющих подключений. To comply with Internet Assigned Numbers Authority (IANA) recommendations, Microsoft has increased the dynamic client port range for outgoing connections. Новый порт запуска по умолчанию — 49152, а конечный порт по умолчанию — 65535. The new default start port is 49152, and the new default end port is 65535. Это изменение конфигурации более ранних версий Windows, которые использовали диапазон портов по умолчанию от 1025 до 5000. This is a change from the configuration of earlier versions of Windows that used a default port range of 1025 through 5000.
Динамический диапазон порта можно просмотреть на компьютере с помощью следующих команд сетки: You can view the dynamic port range on a computer by using the following netsh commands:
- netsh int ipv4 show dynamicport tcp
- netsh int ipv4 show dynamicport udp
- netsh int ipv6 show dynamicport tcp
- netsh int ipv6 show dynamicport udp
Диапазон устанавливается отдельно для каждого транспорта (TCP или UDP). The range is set separately for each transport (TCP or UDP). Диапазон порта теперь — это диапазон, который имеет отправную точку и конечную точку. The port range is now a range that has a starting point and an ending point. Клиенты Майкрософт, развертывавшие серверы с Windows Server, могут иметь проблемы, влияющие на связь RPC между серверами, если брандмауэры используются во внутренней сети. Microsoft customers who deploy servers that are running Windows Server may have problems that affect RPC communication between servers if firewalls are used on the internal network. В этих ситуациях рекомендуется перенастроить брандмауэры, чтобы разрешить трафик между серверами в динамическом диапазоне портов от 49152 до 65535. In these situations, we recommend that you reconfigure the firewalls to allow traffic between servers in the dynamic port range of 49152 through 65535. Этот диапазон помимо известных портов, используемых службами и приложениями. This range is in addition to well-known ports that are used by services and applications. Или диапазон портов, используемый серверами, может быть изменен на каждом сервере. Or, the port range that is used by the servers can be modified on each server. Этот диапазон можно настроить с помощью команды netsh следующим образом. You adjust this range by using the netsh command, as follows. Вышеуказанная команда задает динамический диапазон порта для TCP. The above command sets the dynamic port range for TCP.
Порт запуска — это число, а общее число портов — диапазон. The start port is number, and the total number of ports is range. Ниже приводится пример команд: The following are sample commands:
- netsh int ipv4 set dynamicport tcp start=10000 num=1000
- netsh int ipv4 set dynamicport udp start=10000 num=1000
- netsh int ipv6 set dynamicport tcp start=10000 num=1000
- netsh int ipv6 set dynamicport udp start=10000 num=1000
Эти примерные команды устанавливают динамический диапазон портов для запуска в порте 10000 и окончания в порте 10999 (1000 портов). These sample commands set the dynamic port range to start at port 10000 and to end at port 10999 (1000 ports). Минимальный диапазон портов, который можно установить, — 255. The minimum range of ports that can be set is 255. Минимальный порт запуска, который можно установить, — 1025. The minimum start port that can be set is 1025. Максимальный конечный порт (в зависимости от настраиваемого диапазона) не может превышать 65535. The maximum end port (based on the range being configured) cannot exceed 65535. Чтобы повторить поведение Windows Server 2003 по умолчанию, используйте 1025 в качестве порта запуска, а затем используйте 3976 в качестве диапазона для TCP и UDP. To duplicate the default behavior of Windows Server 2003, use 1025 as the start port, and then use 3976 as the range for both TCP and UDP. Это приводит к запуску порта 1025 и конечного порта 5000. This results in a start port of 1025 and an end port of 5000.
В частности, для исходящие подключения в качестве входящих подключений не потребуется эфемерный порт для приемки подключений. Specifically, about outbound connections as incoming connections will not require an Ephemeral port for accepting connections.
Так как исходящие подключения начинают сбой, вы увидите много ниже поведения: Since outbound connections start to fail, you will see a lot of the below behaviors:
Не удается войти в машину с учетными данными домена, однако вход с локальной учетной записью работает. Unable to sign in to the machine with domain credentials, however sign-in with local account works. Для регистрации домена потребуется связаться с dc для проверки подлинности, которая снова является исходящие подключения. Domain sign-in will require you to contact the DC for authentication which is again an outbound connection. Если у вас есть набор учетных данных кэша, вход в домен может по-прежнему работать. If you have cache credentials set, then domain sign-in might still work.
Сбои обновления групповой политики: Group Policy update failures:
Недоступными являются файлы: File shares are inaccessible:
RDP с пострадавшего сервера не удается: RDP from the affected server fails:
Любое другое приложение, запущенное на компьютере, начнет выдать ошибки Any other application running on the machine will start to give out errors
Перезагрузка сервера позволит решить проблему временно, но все симптомы будут возвращаться через некоторое время. Reboot of the server will resolve the issue temporarily, but you would see all the symptoms come back after a period of time.
Если вы подозреваете, что машина находится в состоянии истощения порта: If you suspect that the machine is in a state of port exhaustion:
Попробуйте сделать исходящие подключения. Try making an outbound connection. На сервере/компьютере можно получить доступ к удаленной совместной информации или попробовать RDP на другом сервере или telnet на сервере в порту. From the server/machine, access a remote share or try an RDP to another server or telnet to a server on a port. Если исходящие подключения не удается для всех этих, перейдите к следующему шагу. If the outbound connection fails for all of these, go to the next step.
Откройте для просмотра событий и в системных журналах и посмотрите события, которые четко указывают текущее состояние: Open event viewer and under the system logs, look for the events which clearly indicate the current state:
а. a. Event ID 4227 Event ID 4227
б. b. ID события 4231 Event ID 4231
Сбор данных netstat -anob output с сервера. Collect a netstat -anob output from the server. Вывод netstat покажет вам огромное количество записей для TIME_WAIT для одного piD. The netstat output will show you a huge number of entries for TIME_WAIT state for a single PID.
После изящного закрытия сеанса или внезапного закрытия сеанса через 4 минуты (по умолчанию) порт, используемый для этого процесса или приложения, будет выпущен обратно в доступный пул. After a graceful closure or an abrupt closure of a session, after a period of 4 minutes (default), the port used the process or application would be released back to the available pool. В течение 4 минут состояние подключения TCP будет TIME_WAIT состояние. During this 4 minutes, the TCP connection state will be TIME_WAIT state. В ситуации, когда вы подозреваете истощение порта, приложение или процесс не смогут освободить все потребляемые порты и останутся в TIME_WAIT состоянии. In a situation where you suspect port exhaustion, an application or process will not be able to release all the ports that it has consumed and will remain in the TIME_WAIT state.
Вы также можете CLOSE_WAIT подключений состояния в одном и том же выходе, однако CLOSE_WAIT состояние — это состояние, когда одна сторона одноранговой сети TCP не имеет больше данных для отправки (fin sent), но может получать данные с другого конца. You may also see CLOSE_WAIT state connections in the same output, however CLOSE_WAIT state is a state when one side of the TCP peer has no more data to send (FIN sent) but is able to receive data from the other end. Это состояние не обязательно указывает на исчерпание порта. This state does not necessarily indicate port exhaustion.
Наличие огромных подключений в TIME_WAIT состоянии не всегда указывает на то, что сервер в настоящее время находится вне портов, если первые две точки не будут проверены. Having huge connections in TIME_WAIT state does not always indicate that the server is currently out of ports unless the first two points are verified. Наличие многких подключений TIME_WAIT указывает на то, что процесс создает большое количество подключений TCP и в конечном итоге может привести к исчерпанию порта. Having lot of TIME_WAIT connections does indicate that the process is creating lot of TCP connections and may eventually lead to port exhaustion.
Netstat был обновлен в Windows 10 с добавлением переключателя -Q, чтобы показать порты, которые перешли из времени ожидания, как в состоянии BOUND. Netstat has been updated in Windows 10 with the addition of the -Q switch to show ports that have transitioned out of time wait as in the BOUND state. Выпущено обновление Windows 8.1 и Windows Server 2012 R2. An update for Windows 8.1 and Windows Server 2012 R2 has been released that contains this functionality. В cmdlet PowerShell Get-NetTCPConnection в Windows 10 также показаны эти порты BOUND. The PowerShell cmdlet Get-NetTCPConnection in Windows 10 also shows these BOUND ports.
До 10/2016 netstat был неточным. Until 10/2016, netstat was inaccurate. Исправления для netstat, от порта до 2012 R2, позволили Netstat.exe и Get-NetTcpConnection правильно сообщать об использовании порта TCP или UDP в Windows Server 2012 R2. Fixes for netstat, back-ported to 2012 R2, allowed Netstat.exe and Get-NetTcpConnection to correctly report TCP or UDP port usage in Windows Server 2012 R2. Дополнительные данные см. в пункте Windows Server 2012 R2: Ephemeral ports hotfixes. See Windows Server 2012 R2: Ephemeral ports hotfixes to learn more.
Откройте командную подсказку в режиме администрирования и запустите приведенную ниже команду Open a command prompt in admin mode and run the below command
Откройте файл server.etl с помощью сетевого монитора и в разделе фильтра применяйте фильтр Wscore_MicrosoftWindowsWinsockAFD.AFD_EVENT_BIND. Status.LENTStatus.Code == 0x209. Open the server.etl file with Network Monitor and in the filter section, apply the filter Wscore_MicrosoftWindowsWinsockAFD.AFD_EVENT_BIND.Status.LENTStatus.Code == 0x209. Вы должны увидеть записи, которые говорят STATUS_TOO_MANY_ADDRESSES. You should see entries which say STATUS_TOO_MANY_ADDRESSES. Если вы не найдете записей, сервер по-прежнему не выходит из портов. If you do not find any entries, then the server is still not out of ports. Если их найти, можно подтвердить, что сервер находится под истощением порта. If you find them, then you can confirm that the server is under port exhaustion.
Устранение неполадок в истощении порта Troubleshoot Port exhaustion
Главное — определить, какой процесс или приложение использует все порты. The key is to identify which process or application is using all the ports. Ниже приведены некоторые средства, которые можно использовать для изоляции одного процесса Below are some of the tools that you can use to isolate to one single process
Метод 1 Method 1
Начните с вывода netstat. Start by looking at the netstat output. Если вы используете Windows 10 или Windows Server 2016, вы можете выполнить команду и проверить для процесса ID, который имеет максимальное количество записей как netstat -anobq BOUND. If you are using Windows 10 or Windows Server 2016, then you can run the command netstat -anobq and check for the process ID which has maximum entries as BOUND. Кроме того, вы также можете запустить команду powershell ниже, чтобы определить процесс: Alternately, you can also run the below Powershell command to identify the process:
Большинство утечек портов вызваны процессами пользовательского режима, которые неправильно закрывают порты, когда произошла ошибка. Most port leaks are caused by user-mode processes not correctly closing the ports when an error was encountered. В портах уровня пользователя (на самом деле розетки) обрабатываются. At the user-mode level ports (actually sockets) are handles. И TaskManager, и ProcessExplorer могут отображать подсчеты обработки, что позволяет определить, какой процесс потребляет все порты. Both TaskManager and ProcessExplorer are able to display handle counts which allows you to identify which process is consuming all of the ports.
Для Windows 7 и Windows Server 2008 R2 можно обновить версию Powershell, чтобы включить вышеуказанное. For Windows 7 and Windows Server 2008 R2, you can update your Powershell version to include the above cmdlet.
Метод 2 Method 2
Если метод 1 не помогает определить процесс (до Windows 10 и Windows Server 2012 R2), то посмотрите на диспетчер задач: If method 1 does not help you identify the process (prior to Windows 10 and Windows Server 2012 R2), then have a look at Task Manager:
Добавьте столбец под названием «ручки» под сведениями и процессами. Add a column called “handles” under details/processes.
Сортировать ручки столбца, чтобы определить процесс с самым большим числом рули. Sort the column handles to identify the process with the highest number of handles. Обычно виновником может быть процесс с ручками более 3000, за исключением таких процессов, как System, lsass.exe, store.exe, sqlsvr.exe. Usually the process with handles greater than 3000 could be the culprit except for processes like System, lsass.exe, store.exe, sqlsvr.exe.
Если какой-либо другой процесс имеет более высокое число, остановите этот процесс, а затем попробуйте войти с помощью учетных данных домена и узнайте, удастся ли ему это сделать. If any other process than these has a higher number, stop that process and then try to login using domain credentials and see if it succeeds.
Метод 3 Method 3
Если диспетчер задач не помог вам определить процесс, используйте Обозреватель процессов для изучения проблемы. If Task Manager did not help you identify the process, then use Process Explorer to investigate the issue.
Действия по использованию проводника процесса: Steps to use Process explorer:
Скачайте Explorer процесса и запустите его с повышенными уровнями. Download Process Explorer and run it Elevated.
Alt + щелкните заглавную колонку, выберите Выберите столбцыи на вкладке Производительность процесса добавьте количество обработок. Alt + click the column header, select Choose Columns, and on the Process Performance tab, add Handle Count.
Выберите Представление \ Показать нижнюю области. Select View \ Show Lower Pane.
Выберите Представление \ Представление нижней области \ Ручки. Select View \ Lower Pane View \ Handles.
Щелкните столбец Ручки для сортировки по этому значению. Click the Handles column to sort by that value.
Изучите процессы с более высоким количеством обрабатываемой обработки, чем остальные (если вы не можете сделать исходящие подключения более 10 000). Examine the processes with higher handle counts than the rest (will likely be over 10,000 if you can’t make outbound connections).
Щелкните, чтобы выделить один из процессов с высоким количеством обработки. Click to highlight one of the processes with a high handle count.
В нижней области окантовки, указанные ниже, являются розетками. In the lower pane, the handles listed as below are sockets. (Sockets — это технически обработки файлов). (Sockets are technically file handles).
Файл \Device\AFD File \Device\AFD
Некоторые из них являются нормальными, но большое число из них не являются (от сотен до тысяч). Some are normal, but large numbers of them are not (hundreds to thousands). Закрой процесс, о чем идет речь. Close the process in question. Если это восстанавливает исходящие подключения, то вы еще раз доказали, что это приложение является причиной. If that restores outbound connectivity, then you have further proven that the app is the cause. Свяжитесь с поставщиком этого приложения. Contact the vendor of that app.
Наконец, если вышеперечисленные методы не помогли изолировать процесс, предлагаем собрать полную свалку памяти машины в состоянии проблемы. Finally, if the above methods did not help you isolate the process, we suggest you collect a complete memory dump of the machine in the issue state. При сбросе будет посвеяно, какой процесс имеет максимальные ручки. The dump will tell you which process has the maximum handles.
В качестве обходного решения перезагрузка компьютера возвращает его в нормальное состояние и поможет вам решить проблему в настоящее время. As a workaround, rebooting the computer will get the it back in normal state and would help you resolve the issue for the time being. Однако при нецелесообразной перезагрузке можно также рассмотреть возможность увеличения количества портов на машине с помощью нижеупомяг. However, when a reboot is impractical, you can also consider increasing the number of ports on the machine using the below commands:
В этом случае динамический диапазон портов будет начинаться в порту 10000 и заканчивается в порте 10999 (1000 портов). This will set the dynamic port range to start at port 10000 and to end at port 10999 (1000 ports). Минимальный диапазон портов, который можно установить, — 255. The minimum range of ports that can be set is 255. Минимальный порт запуска, который можно установить, — 1025. The minimum start port that can be set is 1025. Максимальный конечный порт (в зависимости от настраиваемого диапазона) не может превышать 65535. The maximum end port (based on the range being configured) cannot exceed 65535.
Обратите внимание, что увеличение динамического диапазона портов является не постоянным решением, а временным. Note that increasing the dynamic port range is not a permanent solution but only temporary. Вам потребуется отслеживать, какие процессы и процессоры потребляют максимальное количество портов и устраняют неполадки с точки зрения этого процесса, чтобы понять, почему он потребляет такое большое количество портов. You will need to track down which process/processors are consuming max number of ports and troubleshoot from that process standpoint as to why its consuming such high number of ports.
Для Windows 7 и Windows Server 2008 R2 можно использовать ниже сценарий для сбора вывода netstat с определенной частотой. For Windows 7 and Windows Server 2008 R2, you can use the below script to collect the netstat output at defined frequency. Из выходных данных можно увидеть тенденцию использования порта. From the outputs, you can see the port usage trend.
Полезные ссылки Useful links
Истощение порта и вы! Port Exhaustion and You! — в этой статье приводится подробная информация о состояниях netstat и о том, как можно использовать выход netstat для определения состояния порта — this article gives a detail on netstat states and how you can use netstat output to determine the port status
Обнаружение эфемерного истощенияпорта: в этой статье имеется скрипт, который будет работать в цикле, чтобы сообщить о состоянии порта. Detecting ephemeral port exhaustion: this article has a script which will run in a loop to report the port status. (Применимо для Windows 2012 R2, Windows 8, Windows 10) (Applicable for Windows 2012 R2, Windows 8, Windows 10)