Windows netstat какое приложение слушает порт

How do I find out which process is listening on a TCP or UDP port on Windows?

How do I find out which process is listening on a TCP or UDP port on Windows?

Mateen Ulhaq's user avatar

Mateen Ulhaq

23k16 gold badges89 silver badges130 bronze badges

asked Sep 7, 2008 at 6:26

readonly's user avatar

readonlyreadonly

337k107 gold badges203 silver badges205 bronze badges

13

PowerShell

TCP

Get-Process -Id (Get-NetTCPConnection -LocalPort YourPortNumberHere).OwningProcess

UDP

Get-Process -Id (Get-NetUDPEndpoint -LocalPort YourPortNumberHere).OwningProcess

cmd

 netstat -a -b

(Add -n to stop it trying to resolve hostnames, which will make it a lot faster.)

Note Dane’s recommendation for TCPView. It looks very useful!

-a Displays all connections and listening ports.

-b Displays the executable involved in creating each connection or listening port. In some cases well-known executables host multiple independent components, and in these cases the sequence of components involved in creating the connection or listening port is displayed. In this case the executable name is in [] at the bottom, on top is the component it called, and so forth until TCP/IP was reached. Note that this option can be time-consuming and will fail unless you have sufficient permissions.

-n Displays addresses and port numbers in numerical form.

-o Displays the owning process ID associated with each connection.

Peter Mortensen's user avatar

answered Sep 7, 2008 at 6:28

Brad Wilson's user avatar

21

There’s a native GUI for Windows:

  • Start menu → All ProgramsAccessoriesSystem ToolsResource Monitor

  • or run resmon.exe,

  • or from TaskManagerPerformance tab.

Enter image description here

serge's user avatar

serge

13.2k32 gold badges110 silver badges192 bronze badges

answered May 18, 2014 at 5:02

bcorso's user avatar

bcorsobcorso

44.8k9 gold badges62 silver badges75 bronze badges

10

For Windows:

netstat -aon | find /i "listening"

xash's user avatar

xash

3,68010 silver badges22 bronze badges

answered Sep 7, 2008 at 6:32

aku's user avatar

akuaku

121k32 gold badges171 silver badges203 bronze badges

6

Use TCPView if you want a GUI for this. It’s the old Sysinternals application that Microsoft bought out.

Peter Mortensen's user avatar

answered Sep 7, 2008 at 6:38

Dane's user avatar

DaneDane

9,6515 gold badges27 silver badges22 bronze badges

5

The -b switch mentioned in most answers requires you to have administrative privileges on the machine. You don’t really need elevated rights to get the process name!

Find the pid of the process running in the port number (e.g., 8080)

netstat -ano | findStr "8080"

Find the process name by pid

tasklist /fi "pid eq 2216"

find process by TCP/IP port

Jaywalker's user avatar

Jaywalker

3,0393 gold badges30 silver badges42 bronze badges

answered Jan 24, 2018 at 3:50

Ram Sharma's user avatar

Ram SharmaRam Sharma

2,3771 gold badge8 silver badges7 bronze badges

You can get more information if you run the following command:

netstat -aon | find /i "listening" |find "port"

using the ‘Find’ command allows you to filter the results. find /i "listening" will display only ports that are ‘Listening’. Note, you need the /i to ignore case, otherwise you would type find «LISTENING». | find "port" will limit the results to only those containing the specific port number. Note, on this it will also filter in results that have the port number anywhere in the response string.

Peter Mortensen's user avatar

answered Oct 8, 2013 at 18:56

Nathan24's user avatar

Nathan24Nathan24

1,35011 silver badges20 bronze badges

4

  1. Open a command prompt window (as Administrator) From «StartSearch box» Enter «cmd» then right-click on «cmd.exe» and select «Run as Administrator»

  2. Enter the following text then hit Enter.

    netstat -abno

    -a Displays all connections and listening ports.

    -b Displays the executable involved in creating each connection or
    listening port. In some cases well-known executables host
    multiple independent components, and in these cases the
    sequence of components involved in creating the connection
    or listening port is displayed. In this case the executable
    name is in [] at the bottom, on top is the component it called,
    and so forth until TCP/IP was reached. Note that this option
    can be time-consuming and will fail unless you have sufficient
    permissions.

    -n Displays addresses and port numbers in numerical form.

    -o Displays the owning process ID associated with each connection.

  3. Find the Port that you are listening on under «Local Address»

  4. Look at the process name directly under that.

NOTE: To find the process under Task Manager

  1. Note the PID (process identifier) next to the port you are looking at.

  2. Open Windows Task Manager.

  3. Select the Processes tab.

  4. Look for the PID you noted when you did the netstat in step 1.

    • If you don’t see a PID column, click on View / Select Columns. Select PID.

    • Make sure “Show processes from all users” is selected.

answered Nov 8, 2012 at 1:49

Cyborg's user avatar

CyborgCyborg

1,23412 silver badges12 bronze badges

Get PID and Image Name

Use only one command:

for /f "tokens=5" %a in ('netstat -aon ^| findstr 9000') do tasklist /FI "PID eq %a"

where 9000 should be replaced by your port number.

The output will contain something like this:

Image Name                     PID Session Name        Session#    Mem Usage
========================= ======== ================ =========== ============
java.exe                      5312 Services                   0    130,768 K

Explanation:

  • it iterates through every line from the output of the following command:

    netstat -aon | findstr 9000
    
  • from every line, the PID (%a — the name is not important here) is extracted (PID is the 5th element in that line) and passed to the following command

    tasklist /FI "PID eq 5312"
    

If you want to skip the header and the return of the command prompt, you can use:

echo off & (for /f "tokens=5" %a in ('netstat -aon ^| findstr 9000') do tasklist /NH /FI "PID eq %a") & echo on

Output:

java.exe                      5312 Services                   0    130,768 K

answered Feb 10, 2016 at 10:17

ROMANIA_engineer's user avatar

ROMANIA_engineerROMANIA_engineer

52.9k28 gold badges199 silver badges194 bronze badges

1

First we find the process id of that particular task which we need to eliminate in order to get the port free:

Type

netstat -n -a -o

After executing this command in the Windows command line prompt (cmd), select the pid which I think the last column. Suppose this is 3312.

Now type

taskkill /F /PID 3312

You can now cross check by typing the netstat command.

NOTE: sometimes Windows doesn’t allow you to run this command directly on CMD, so first you need to go with these steps:

From the start menu -> command prompt (right click on command prompt, and run as administrator)

Peter Mortensen's user avatar

answered Aug 23, 2014 at 15:25

Pankaj Pateriya's user avatar

1

With PowerShell 5 on Windows 10 or Windows Server 2016, run the Get-NetTCPConnection cmdlet. I guess that it should also work on older Windows versions.

The default output of Get-NetTCPConnection does not include Process ID for some reason and it is a bit confusing. However, you could always get it by formatting the output. The property you are looking for is OwningProcess.

  • If you want to find out the ID of the process that is listening on port 443, run this command:

      PS C:> Get-NetTCPConnection -LocalPort 443 | Format-List
    
      LocalAddress   : ::
      LocalPort      : 443
      RemoteAddress  : ::
      RemotePort     : 0
      State          : Listen
      AppliedSetting :
      OwningProcess  : 4572
      CreationTime   : 02.11.2016 21:55:43
      OffloadState   : InHost
    
  • Format the output to a table with the properties you look for:

      PS C:> Get-NetTCPConnection -LocalPort 443 | Format-Table -Property LocalAddress, LocalPort, State, OwningProcess
    
      LocalAddress LocalPort  State OwningProcess
      ------------ ---------  ----- -------------
      ::                 443 Listen          4572
      0.0.0.0            443 Listen          4572
    
  • If you want to find out a name of the process, run this command:

      PS C:> Get-Process -Id (Get-NetTCPConnection -LocalPort 443).OwningProcess
    
      Handles  NPM(K)    PM(K)      WS(K)     CPU(s)     Id  SI ProcessName
      -------  ------    -----      -----     ------     --  -- -----------
      143      15     3448      11024              4572   0 VisualSVNServer
    

answered Nov 2, 2016 at 19:19

Plimpus's user avatar

PlimpusPlimpus

29.4k12 gold badges105 silver badges149 bronze badges

To get a list of all the owning process IDs associated with each connection:

netstat -ao |find /i "listening"

If want to kill any process have the ID and use this command, so that port becomes free

Taskkill /F /IM PID of a process

Peter Mortensen's user avatar

answered Apr 17, 2014 at 14:38

Monis Majeed's user avatar

Monis MajeedMonis Majeed

1,31814 silver badges21 bronze badges

1

It is very simple to get the port number from a PID in Windows.

The following are the steps:

  1. Go to run → type cmd → press Enter.

  2. Write the following command…

    netstat -aon | findstr [port number]
    

    (Note: Don’t include square brackets.)

  3. Press Enter

  4. Then cmd will give you the detail of the service running on that port along with the PID.

  5. Open Task Manager and hit the service tab and match the PID with that of the cmd, and that’s it.

Peter Mortensen's user avatar

answered May 30, 2016 at 6:36

Nishat Lakhani's user avatar

Nishat LakhaniNishat Lakhani

7131 gold badge8 silver badges20 bronze badges

0

netstat -aof | findstr :8080 (Change 8080 for any port)

answered Feb 16, 2021 at 23:59

David Jesus's user avatar

David JesusDavid Jesus

1,8312 gold badges28 silver badges33 bronze badges

To find out which specific process (PID) is using which port:

netstat -anon | findstr 1234

Where 1234 is the PID of your process. [Go to Task Manager → Services/Processes tab to find out the PID of your application.]

Peter Mortensen's user avatar

answered Dec 14, 2018 at 6:55

Talha Imam's user avatar

Talha ImamTalha Imam

9861 gold badge20 silver badges22 bronze badges

2

In case someone need an equivalent for macOS like I did, here is it:

lsof -i tcp:8080

After you get the PID of the process, you can kill it with:

kill -9 <PID>

answered Aug 12, 2020 at 11:22

Benjamin Wen's user avatar

Benjamin WenBenjamin Wen

3,2773 gold badges27 silver badges48 bronze badges

2

Just open a command shell and type (saying your port is 123456):

netstat -a -n -o | find "123456"

You will see everything you need.

The headers are:

 Proto  Local Address          Foreign Address        State           PID
 TCP    0.0.0.0:37             0.0.0.0:0              LISTENING       1111

This is as mentioned here.

Peter Mortensen's user avatar

answered Jan 25, 2017 at 0:13

Tajveer Singh Nijjar's user avatar

1

If you’d like to use a GUI tool to do this there’s Sysinternals’ TCPView.

Peter Mortensen's user avatar

answered Sep 7, 2008 at 6:40

David Webb's user avatar

David WebbDavid Webb

189k57 gold badges309 silver badges298 bronze badges

  1. Open the command prompt — start → Runcmd, or start menu → All ProgramsAccessoriesCommand Prompt.

  2. Type

    netstat -aon | findstr '[port_number]'
    

Replace the [port_number] with the actual port number that you want to check and hit Enter.

  1. If the port is being used by any application, then that application’s detail will be shown. The number, which is shown at the last column of the list, is the PID (process ID) of that application. Make note of this.
  2. Type

    tasklist | findstr '[PID]'
    

Replace the [PID] with the number from the above step and hit Enter.

  1. You’ll be shown the application name that is using your port number.

Peter Mortensen's user avatar

answered May 9, 2019 at 12:18

Anatole ABE's user avatar

Anatole ABEAnatole ABE

5751 gold badge7 silver badges12 bronze badges

2

Netstat:

  • -a displays all connection and listening ports
  • -b displays executables
  • -n stop resolve hostnames (numerical form)
  • -o owning process

    netstat -bano | findstr "7002"
    
    netstat -ano > ano.txt 
    

The Currports tool helps to search and filter

Peter Mortensen's user avatar

answered Sep 23, 2018 at 5:05

Blue Clouds's user avatar

Blue CloudsBlue Clouds

6,7402 gold badges57 silver badges95 bronze badges

Type in the command: netstat -aon | findstr :DESIRED_PORT_NUMBER

For example, if I want to find port 80: netstat -aon | findstr :80

This answer was originally posted to this question.

Peter Mortensen's user avatar

answered Nov 22, 2016 at 15:36

Technotronic's user avatar

TechnotronicTechnotronic

8,1443 gold badges40 silver badges53 bronze badges

netstat -ao and netstat -ab tell you the application, but if you’re not a system administrator you’ll get «The requested operation requires elevation».

It’s not ideal, but if you use Sysinternals’ Process Explorer you can go to specific processes’ properties and look at the TCP tab to see if they’re using the port you’re interested in. It is a bit of a needle and haystack thing, but maybe it’ll help someone…

Peter Mortensen's user avatar

answered Mar 13, 2014 at 19:57

Tony Delroy's user avatar

Tony DelroyTony Delroy

101k15 gold badges174 silver badges249 bronze badges

1

I recommend CurrPorts from NirSoft.

CurrPorts can filter the displayed results. TCPView doesn’t have this feature.

Note: You can right click a process’s socket connection and select «Close Selected TCP Connections» (You can also do this in TCPView). This often fixes connectivity issues I have with Outlook and Lync after I switch VPNs. With CurrPorts, you can also close connections from the command line with the «/close» parameter.

answered Jun 29, 2015 at 22:07

Josh's user avatar

JoshJosh

2,0522 gold badges21 silver badges20 bronze badges

0

A single-line solution that helps me is this one. Just substitute 3000 with your port:

$P = Get-Process -Id (Get-NetTCPConnection -LocalPort 3000).OwningProcess; Stop-Process $P.Id

Edit: Changed kill to Stop-Process for more PowerShell-like language

answered Feb 3, 2019 at 14:46

Angel Venchev's user avatar

Angel VenchevAngel Venchev

6871 gold badge9 silver badges18 bronze badges

2

Using Windows’ default shell (PowerShell) and without external applications

For those using PowerShell, try Get-NetworkStatistics:

> Get-NetworkStatistics | where Localport -eq 8000


ComputerName  : DESKTOP-JL59SC6
Protocol      : TCP
LocalAddress  : 0.0.0.0
LocalPort     : 8000
RemoteAddress : 0.0.0.0
RemotePort    : 0
State         : LISTENING
ProcessName   : node
PID           : 11552

Peter Mortensen's user avatar

answered Aug 25, 2016 at 13:36

mikemaccana's user avatar

mikemaccanamikemaccana

103k93 gold badges371 silver badges470 bronze badges

3

To find pid who using port 8000

netstat -aon | findstr '8000'

To Kill that Process in windows

taskkill /pid pid /f

where pid is the process id which you get form first command

answered Jul 14, 2020 at 6:13

jiz's user avatar

jizjiz

1892 silver badges6 bronze badges

2

Follow these tools: From cmd: C:> netstat -anob with Administrator privileges.

Process Explorer

Process Dump

Port Monitor

All from sysinternals.com.

If you just want to know process running and threads under each process, I recommend learning about wmic. It is a wonderful command-line tool, which gives you much more than you can know.

Example:

c:> wmic process list brief /every:5

The above command will show an all process list in brief every 5 seconds. To know more, you can just go with /? command of windows , for example,

c:> wmic /?
c:> wmic process /?
c:> wmic prcess list /?

And so on and so forth. :)

1

PowerShell

If you want to have a good overview, you can use this:

Get-NetTCPConnection -State Listen | Select-Object -Property *, `
    @{'Name' = 'ProcessName';'Expression'={(Get-Process -Id $_.OwningProcess).Name}} `
    | select ProcessName,LocalAddress,LocalPort

Then you get a table like this:

ProcessName              LocalAddress  LocalPort
-----------              ------------  ---------
services                 ::                49755
jhi_service              ::1               49673
svchost                  ::                  135
services                 0.0.0.0           49755
spoolsv                  0.0.0.0           49672

For UDP, it is:

Get-NetUDPEndpoint | Select-Object -Property *, `
   @{'Name' = 'ProcessName';'Expression'={(Get-Process -Id $_.OwningProcess).Name}} `
   | select ProcessName,LocalAddress,LocalPort

Peter Mortensen's user avatar

answered Feb 27, 2022 at 22:16

Oliver Gaida's user avatar

Oliver GaidaOliver Gaida

1,4426 silver badges12 bronze badges

Use:

netstat -a -o

This shows the PID of the process running on a particular port.

Keep in mind the process ID and go to Task Manager and services or details tab and end the process which has the same PID.

Thus you can kill a process running on a particular port in Windows.

Peter Mortensen's user avatar

answered Aug 13, 2013 at 2:32

nisha's user avatar

nishanisha

6932 gold badges14 silver badges28 bronze badges

You can also check the reserved ports with the command below. Hyper-V reserve some ports, for instance.

netsh int ipv4 show excludedportrange protocol=tcp

Peter Mortensen's user avatar

answered Nov 24, 2020 at 14:50

Daniel Genezini's user avatar

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

tasklist - найти процесс, который слушает порт в windows

Можно заменить все указанные выше команды одной:

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:Temptinywebtinyweb-1-94

команда позволяет найти путь к exe файу в windows

Обновлено 26.06.2017

Утилита netstat или как определить какие порты слушает ваш компьютер. Сетевые утилиты 4 часть-01

Утилита netstat или как определить какие порты слушает ваш компьютер. Сетевые утилиты 4 часть-01

Всем привет ранее я начал рассказ про сетевые утилиты системного администратора в статье «Утилита pathping или как диагностировать проблему на маршруте до сайта. Сетевые утилиты 3 часть», движемся дальше и разбираем еще одну утилиту netstat или, как определить какие порты слушает ваш компьютер. Данная программка, будет не заменимым инструментом в багаже софта, любого системного инженера, поможет ему провести быструю диагностику ситуации и обнаружить ряд всевозможных проблем с сервисами и их доступностью.

Команды netstat

Netstat — Отображение активных подключений TCP, портов, прослушиваемых компьютером, статистики Ethernet, таблицы маршрутизации IP, статистики IPv4 (для протоколов IP, ICMP, TCP и UDP) и IPv6 (для протоколов IPv6, ICMPv6, TCP через IPv6 и UDP через IPv6)

Представим ситуацию вы установили например MSM LSI утилиту для просмотра параметров RAID контроллера, запускаете утилиту, но ничего она не находит, потому что закрыт порт а какой вы не в курсе, и не всегда в инете можно быстро найти информацию об этом, для этого вы и может запустить netstat и посмотреть какой порт слушает ваш сервер с MSM процессом.

Открываем командную строку Windows и вводим netstat ?. У вас выскочит справка утилиты.

Утилита netstat или как определить какие порты слушает ваш компьютер. Сетевые утилиты 4 часть-02

Утилита netstat или как определить какие порты слушает ваш компьютер. Сетевые утилиты 4 часть-02

C:Userssem>netstat ?

Отображение статистики протокола и текущих сетевых подключений TCP/IP.

NETSTAT [-a] [-b] [-e] [-f] [-n] [-o] [-p протокол] [-r] [-s] [-x] [-t]
[интервал]

  • -a Отображение всех подключений и портов прослушивания.
  • -b Отображение исполняемого файла, участвующего в создании
  • каждого подключения или порта прослушивания. Иногда известные исполняемые файлы содержат множество независимых компонентов. Тогда отображается последовательность компонентов, участвующих в создании подключения или порта прослушивания. В этом случае имя исполняемого файла находится снизу в скобках [], сверху находится вызванный им компонент, и так до тех пор, пока не достигнут TCP/IP. Заметьте, что такой подход может занять много времени и требует достаточных разрешений.
  • -e Отображение статистики Ethernet. Может применяться вместе с параметром -s.
  • -f Отображение полного имени домена (FQDN) для внешних адресов.
  • -n Отображение адресов и номеров портов в числовом формате.
  • -o Отображение ИД процесса каждого подключения.
  • -p протокол Отображение подключений для протокола, задаваемых этим параметром. Допустимые значения: TCP, UDP, TCPv6 или UDPv6. Если используется вместе с параметром -s для отображения статистики по протоколам, допустимы следующие значения: IP, IPv6, ICMP, ICMPv6, TCP, TCPv6, UDP или UDPv6.
  • -r Отображение содержимого таблицы маршрутов.
  • -s Отображение статистики по протоколам. По умолчанию статистика отображается для протоколов IP, IPv6, ICMP, ICMPv6, TCP, TCPv6, UDP и UDPv6. Параметр -p позволяет указать подмножество выводимых данных.
  • -t Отображение состояния разгрузки для текущего подключения.
  • -x Отображение подключений, прослушивателей и общих конечных точек NetworkDirect.
  • -y Отображение шаблона подключений TCP для всех подключений. Не может использоваться вместе с другими параметрами. interval Повторное отображение выбранной статистики с паузой между отображениями, заданной интервалом в секундах. Чтобы прекратить повторное отображение статистики, нажмите клавиши CTRL+C. Если этот параметр опущен, netstat напечатает текущую информацию о конфигурации один раз.

Давайте посмотрим интересные ключи утилиты netstat. Первое что вводим

и у нас на экране появится статистика сетевых пакетов ethernet.

Утилита netstat или как определить какие порты слушает ваш компьютер. Сетевые утилиты 4 часть-03

Утилита netstat или как определить какие порты слушает ваш компьютер. Сетевые утилиты 4 часть-03

Если добавим ключ -s то получим статистику по протоколам.

Утилита netstat или как определить какие порты слушает ваш компьютер. Сетевые утилиты 4 часть-04

Утилита netstat или как определить какие порты слушает ваш компьютер. Сетевые утилиты 4 часть-04

Утилита netstat или как определить какие порты слушает ваш компьютер. Сетевые утилиты 4 часть-05

Утилита netstat или как определить какие порты слушает ваш компьютер. Сетевые утилиты 4 часть-05

Очень полезно посмотреть все что слушает ваш хост для этого пишем

Вывод команды содержит Тип протокола либо TCP либо UDP, локальный адрес с портом который слушается и внешний адрес с портом и состояние действия.

Для полного понимания информации, предоставляемой этой командой, необходимо понять принципы установки соединения в протоколе TCP/IP. Вот основные этапы процесса установки соединения TCP/IP:

1. При попытке установить соединение клиент отправляет сообщение SYN серверу.

2. Сервер отвечает собственным сообщением SYN и подтверждением (ACK).

3. После этого клиент отправляет сообщение ACK обратно на сервер, завершая процесс установки соединения.

Процесс разрыва соединения состоит из следующих этапов:

1. Клиент сообщает «Я закончил», отправляя сообщение FIN серверу. На этом этапе клиент только принимает данные от сервера, но сам ничего не отправляет.

2. После этого сервер отправляет сообщение ACK и отправляет собственное сообщение FIN клиенту.

3. После этого клиент отправляет сообщение ACK серверу, подтверждая запрос сервера FIN.

4. При получении сообщения ACK от клиента сервер закрывает соединение.

Понимание этапов процесса установки и разрыва соединения позволяет более прозрачно интерпретировать состояния соединений в выводе команды netstat. Соединения в списке могут находиться в следующих состояниях.

  • CLOSE_WAIT — указывает на пассивную фазу закрытия соединения, которая начинается после получения сервером сообщения FIN от клиента.
  • CLOSED — соединение прервано и закрыто сервером.
  • ESTABLISHED — клиент установил соединение с сервером, получив от сервера сообщение SYN.
  • FIN_WAIT_1 — клиент инициировал закрытие соединения (отправил сообщение FIN).
  • FIN_WAIT_2 — клиент получил сообщения ACK и FIN от сервера.
  • LAST_ACK — сервер отправил сообщение FIN клиенту.
  • LISTEN — сервер готов принимать входящие соединения.
  • SYN_RECEIVED — сервер получил сообщение SYN от клиента и отправил ему ответ.
  • TIMED_WAIT — клиент отправил сообщение FIN серверу и ожидает ответа на это сообщение.
  • YN_SEND — указанное соединение активно и открыто.

Утилита netstat или как определить какие порты слушает ваш компьютер. Сетевые утилиты 4 часть-06

Утилита netstat или как определить какие порты слушает ваш компьютер. Сетевые утилиты 4 часть-06

Если добавить ключ -f то будут разрешаться имена удаленных внешних ресурсов

Утилита netstat или как определить какие порты слушает ваш компьютер. Сетевые утилиты 4 часть-07

Утилита netstat или как определить какие порты слушает ваш компьютер. Сетевые утилиты 4 часть-07

также можно вывести только TCP порты

Утилита netstat или как определить какие порты слушает ваш компьютер. Сетевые утилиты 4 часть-08

Утилита netstat или как определить какие порты слушает ваш компьютер. Сетевые утилиты 4 часть-08

Или UDP порты

Утилита netstat или как определить какие порты слушает ваш компьютер. Сетевые утилиты 4 часть-09

Утилита netstat или как определить какие порты слушает ваш компьютер. Сетевые утилиты 4 часть-09

Вот такая вот полезная утилиты с которой вы всегда будите знать по каким портам общаются службы на хосте. Читайте далее Утилита TCPView. Как определить какие порты слушает ваш компьютер. Сетевые утилиты 5 часть

Материал сайта pyatilistnik.org

На днях снова поступил вопрос: Как узнать что слушает TCP/IP порт в Windows?

Я уже когда-то писал об этом, но видать пришло время сделать это еще раз…

Задача: узнать процесс, который занял конкретный порт.

Решение: воспользуемся командной строкой, чтобы увидеть, какие порты используются в данный момент и имеют специальный флаг, который говорит нам, какой порт назначен на каждый номер идентификатора процесса Windows. Тогда мы можем использовать этот номер, чтобы найти, какой именно это процесс.

Откройте командную строку и введите следующее, возможно, придется запустить ее в режиме администратора, чтобы увидеть все процессы:

NETSTAT -AON | MORE

Если вы посмотрите на правую часть, то вы увидите список PID-ов или идентификаторов процессов. Найдите тот, который привязан к порту, с которым вы работаете, вы увидите 0.0.0.0:80 или порт 80, его PID — 4708.

Теперь вы можете просто открыть диспетчер задач, возможно, придется использовать опцию Показать процессы для всех пользователей, и тогда вы сможете найти PID в списке.

Есть еще один вариант:

Например C:>netstat -an|findstr /i listen

Подробней читаем здесь: http://dosprompt.info/network/netstat.example.asp

Всем хорошей работы !!!


08.08.2012 —


Posted by |
ms windows server 2008

Sorry, the comment form is closed at this time.

На компьютере может быть установлено довольно много программ и все они резервируют в операционной системе определенный порт для взаимодействия с другим программным обеспечением по сети. В большинстве случаев пользователь заранее знает какой порт использует программа. Это может быть официально зарезервированный порт, под определенный сетевой протокол. Например почтовые программы используют для приема почты протокол POP3 и резервируют порт 110. Бывают неофициально резервируемые порты, например порт 1540 используемый агентом сервера 1С:Предприятие. Информацию об используемых неофициальных портах разработчики программного обеспечения указывают в документации.

Определения порта программы стандартными средствами Windows

Узнать какой порт использует программа в операционной системе Windows можно используя инструменты командной строки — tasklist и netstat. С помощью tasklist узнаем номер идентификатора процесса — PID, затем в netstat находим номер порта этого процесса.

Поиск идентификатора процесса PID

1. Открываем командную строку: сочетание клавиш <Win +R> и вводим команду CMD.

запуск командной строки wondows

2. Запускаем tasklist и находим PID процесса.

Если необходимо отобразить полный список процессов, в том числе служебных и системных, необходимо использовать tasklist без аргументов.

tasklist

Команда tasklist /fi «status eq running» найдет только те процессы, которые были запущенны программами. Это сократит список процессов и облегчит поиск.

tasklist /fi "status eq running"

Находим в списке нужную программу, например OneDrive.exe и запоминаем соответствующий PID.

список активных процессов

Поиск порта процесса

Для получения списка используемых портов воспользуемся утилитой командной строки netstat.

netstat -aon

B netstat были использованы слtдующие аргументы:

-a — показывает все сокеты, используемые процессами
-o — показывает PID процесса
-n — показывает адреса в числовом формате

В результате будет получен довольно крупный список активных сетевых соединений, среди которых необходимо найти соединение с нужным PID.

список активных сетевых соединений

Чтобы отфильтровать список и сразу найти сетевое соединение с нужным PID перенаправим результаты netstat в утилиту findstr «PID_number», где PID_number — идентификатор искомого процесса.

netstat -aon | findstr "15304"
фильтр списка сетевых соединений по PID

В найденных результатах видно, что процесс c PID 15304 (программа OneDrive.exe) использует несколько сетевых портов: 11906, 11907, 11908.

Обращайте внимание на то, для какого траспортного протокола открыт порт: ТСР или UDP. Это информация будет важна, когда будете пробрасывать порт через межсетевой экран.

Программы для просмотра сетевых соединений

Этот способ подойдет для тех, кто не хочет погружаться в работу утилит командной строки Windows, а желает быстро и просто получить информацию о портах, которые использует программа, в графическом интерфейсе.

Без труда в интернете можно найти 2 бесплатные программы для полчения списка сетевых соединений операционной системы — это «TCPView» и «Curr ports».

TCPView

TCPView — программа из набора утилит Sysinternals от Марка Руссиновича, с некоторых пор ставшей частью самого Microsoft. Программа не требует установки, занимает небольшой объем дискового пространства и скачать ее можно с официального сайта Майкрософт: https://docs.microsoft.com/ru-ru/sysinternals/downloads/tcpview.

После запуска программы будет сразу показан список всех сетевых соединений процессов с информацией о протоколе, локальном и удаленном адресе, локальном и удаленном порте соединения. Список можно фильтровать, сортировать и следить за изменениями онлайн. В дополнение к этому можно убить какой-либо процесс или определить кому принадлежит ip-адрес хоста, с которым установлено соединение.

Из мелких недостатков — отсутствие русского языка.

как найти порт в TCPView

CurrPorts

CurrPorts — программа от проекта под названием NirSoft, который так же специализируется на разработке простых и бесплатных утилит для Windows. Программа так же не требует установки, мало весит и в целом очень похожа на TCPView, но имеет более аскетичный интерфейс. Скачать программу можно с официального сайта проекта: https://www.nirsoft.net/utils/cports.html#DownloadLinks.

Из плюсов программы следует отметить наличие русского языка. Чтобы русифицировать программу нужно скачать отдельный файл русификации и положить его в папку с программой.

как определить порт с помощью CurrPorts

Остались вопросы или что-то непонятно — смело оставляйте комментарии.

Connections between applications work much like conversations between humans. The conversation is started by someone speaking. If no one is listening, then the conversation doesn’t get far. How do you know who’s listening on a Windows PC? The Netstat command-line utility and the PowerShell Get-NetTCPConnection cmdlet.

Not a reader? Watch this related video tutorial!

Not seeing the video? Make sure your ad blocker is disabled.

In this tutorial, you will learn how to inspect listening ports and established TCP connections on your Windows computer with Netstat and the native PowerShell command Get-NetTCPConnection.

If you’re an IT pro struggling with too many password reset requests in Active Directory, check out Specops uReset, a secure SSPR solution.

Prerequisites

If you’d like to follow along with examples in this tutorial, be sure you have:

  • A Windows PC. Any version will do. This tutorial is using Windows 10 Build 21343.1
  • PowerShell. Both Windows PowerShell and PowerShell 6+ should work. This tutorial us using PowerShell v7.2.0-preview.2

Using Netstat to Find Active and Listening Ports

Netstat is one of those command-line utilities that seems like it’s been around forever. It’s been a reliable command-line utility to inspect local network connections for a long time. Let’s check out how to use it to find listening and established network connections.

Netstat has many different parameters. This tutorial will only use three of them. To learn more about what netstat can do, run netstat /?.

Assuming you’re on a Windows PC:

1. Open up an elevated command prompt (cmd.exe).

2. Run netstat -a to find all of the listening and established connections on the PC. By default, netstat only returns listening ports. Using the -a parameter tells netstat to return listening and established connections.

Run the Netstat -a
Run the Netstat -a

The output above is broken out into four columns:

  • Proto – shows either UDP or TCP to indicate the type of protocol used.
  • Local Address – shows the local IP address and port that is listening. For many services, this will be 0.0.0.0 for the IP part, meaning it is listening on all network interfaces. In some cases, a service will only listen on a single Network Interface (NIC). In that case, netstat will show the IP address of the NIC. A colon separates the IP address from the port that it is listening on.
  • Foreign Address – shows the remote IP address the local connection is communicating with. If the Foreign Address is 0.0.0.0:0, the connection is listening for all IPs and all ports. For established connections, the IP of the client machine will be shown.
  • State – shows the state the port is in, usually this will be LISTENING or ESTABLISHED.

3. Now run netstat -an. You should now see that any names in the output have been turned into IP addresses. By default, netstat attempts to resolve many IP addresses to names.

run netstat -an
run netstat -an

4. Finally, perhaps you’d like to know the Windows processes that are listening or have these connections open. To find that, use the -b switch.

Using the -b switch requires an elevated command prompt or PowerShell prompt. You will get the error The requested operation requires elevation if you use the -b switch in a non-elevated prompt.

netstat -anb
netstat -anb

Using PowerShell to Find Active and Listening Ports

Now that you’ve got a chance to see how the old-school netstat utility shows active and listening ports, let’s see how to do it in PowerShell.

Using PowerShell gives you a lot more control to see just what you want, rather than having to scroll through long lists of output. The Get-NetTCPConnection cmdlet is much more specific than netstat about what you want to see.

This tutorial isn’t going to cover all of the parameters that come with the Get-NetTCPConnection cmdlet. If you’re curious, run Get-Help Get-NetTCPConnection -Detailed to discover more examples.

On your Windows PC:

1. Open up a PowerShell console as administrator.

The only reason you need to elevate a PowerShell console is to see the program that owns the connection (like the netstat -b parameter).

2. Run Get-NetTcpConnection. You’ll see output similar to what netstat provided. Instead of just a big string of output, Get-NetTcpConnection returns a list of PowerShell objects.

You can now see the same general information that netstat provided you by now; by default, you have information on the OwningProcess (the -b switch on netstat) and the AppliedSetting field, which relates to the network profile the connection is a part of.

Unlike netstat, the Get-NetTCPConnection cmdlet will now show listening UDP connections.

Get-NetTCPConnection
Get-NetTCPConnection

3. Pipe the output to Select-Object showing all properties. You’ll see PowerShell returns a lot more information that netstat did.

Get-NetTCPConnection | Select-Object -Property *
Pipe the output to Select-Object
Pipe the output to Select-Object

4. Now, narrow down the output to just listening ports.

Get-NetTCPConnection -State Listen
narrow down the output
narrow down the output

5. Now, find the process names for the OwningProcess fields. To do that, run the Get-Process cmdlet and provide the process ID as shown below.

Get-Process cmdlet
Get-Process cmdlet

If you’d like to create another property for the process name, you could optionally use a Select-Object calculated field.

Get-NetTCPConnection | Select-Object -Property *,@{'Name' = 'ProcessName';'Expression'={(Get-Process -Id $_.OwningProcess).Name}}

6. Narrow down the states to a bit more by finding Listening and Established states by defining the State parameter value as a comma-delimited list.

Get-NetTCPConnection -State Listen,Established

7. Finally, limit the connections down by the port the connection is connected to with the RemotePort parameter.

Use the LocalPort parameter to filter connections by local port. Get-NetTCPConnection -RemotePort 443

Get-NetTCPConnection -RemotePort 443
RemotePort parameter
RemotePort parameter

If you’re an IT pro struggling with too many password reset requests in Active Directory, check out Specops uReset, a secure SSPR solution.

Conclusion

You have now seen how the Netstat utility and the Get-NetTCPConnection PowerShell cmdlet help you find local network connections.

Now that you can show the processes running on a server combine this with the Test-NetConnection PowerShell cmdlet to get an end-to-end view of connectivity between a client and server.

Whenever an application wants to make itself accessible over the network, it claims a TCP/IP port, which means that port can’t be used by anything else. So if you need to use an in-use port, how do you tell what application is holding it?

There’s a number of ways to tell which application has the port locked, here we will use a windows built-in way using the command line and Task Manager.

Using Built-In Tools to See What is Listening on a Port

The first step is to use a command-line tool to see what ports are in use, and use a special flag that tells us which port is assigned to each Windows process identifier number. Then we can use that number to look up exactly which process it is.

Open up a command prompt and type in the following—you may have to open in Administrator mode to see all processes:

p1

netstat -ab | more

This will immediately show you a list, although it’s maybe a little complicated. You’ll see the process name in the list, and you can search for it.

p4

You can also use this other method, which takes an extra step, but makes it easier to locate the actual process:


netstat -aon | more

If you look on the right-hand side, you’ll see where I’ve highlighted the list of PIDs, or Process Identifiers. Find the one that’s bound to the port that you’re trying to troubleshoot—for this example, you’ll see that 0.0.0.0:80, or port 80, is in use by PID 1184.

p2

Now you can simply open up Task Manager—you might have to use the option to Show Processes for All Users, and then you’ll be able to find the PID in the list. Once you’re there, you can use the End Process, Open File Location, or Go to Service(s) options to control the process or stop it.

p5

Alternatively you can even use resource monitor to stop any process that is running. To open resource monitor type resmon.exe in run. This will bring up the resource monitor window.

p6

p3

There would be situations were some other process is running at port 80. To stop anything running in port 80 the following command can be used from command prompt.

net stop http /y

Frequently Asked Questions (FAQs)

What application is listening on a TCP IP port in Windows?
Netstat is a diagnostic tool that creates a list of open ports that the machine is listening to, as well as the ports it is currently connected to on other machines.  In Netstat, stat stands for state or statistics, which tells you the current network status of every TCP connection.

How do I find out what application is using a TCP port?
You can use Netstat -b -a -o.

This tool provides a list of all open ports and their associated processes. The -o shows the process id, which you can look up in your task manager or processes tab. To end that process, simply enter taskkill /PID xxxx.

How can I tell if a server is listening on a port?
On the server itself, use Netstat -an to check to see which ports are listening. From outside the server, telnet host port can be used to check connections. A refused connection means nothing is running, whereas an accepted connection means something is running. Timeout implies a firewall is blocking access.

How do I find out what application is using port 8080?
Open the diagnostic tool, netstat -ano. This tool will list the PID (Process Identifier) that is listening to port 80. Open the Task Manager’s Processes tab. Select “View” and “Select Columns” menu. Activate the PID column to see the name of the process listening on port 80.

Is Port 8080 http or https?
Port 8080 is a non-standard, high number port that is popular as an alternative port for HTTP servers, most often application servers. Port 8443 is a default alternative port for HTTPS servers. It can also be used as an alternative port for any protocol like ssh, FTP, NTP, BOOTP, etc.

Why is port 8080 default?
Historically, only authorized system administrators were able to establish and operate a web server on port 80, since this was within the first 1023-port privileged region. When non-administrators wished to run their own web servers, they often chose port 8080 to host a secondary or alternate web server.

Понравилась статья? Поделить с друзьями:
  • Windows movie maker скачать 64 бит для виндовс 10
  • Windows nashville build 999 windows 96
  • Windows movie maker с какими файлами работает
  • Windows must have программы для windows
  • Windows movie maker программа для создания анимации