Как найти процесс который занял порт

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

Вернуться назад ОСНОВНОЙ ТЕКСТ СТАТЬИ

Версия для печати

Как определить каким процессом (программой) занят порт.

Требования.

Статья применима для Windows 2000/XP/Vista/7.

Информация.
При установке некоторых программ иногда возникает
проблема с доступностью порта. Т.е. вы устанавливаете программу, а она вам
говорит: «Извините, но предпочитаемый порт номер <такой
то> занят!». И самое интересное программа не говорит
чем или кем занят порт.

Как определить каким процессом (программой) занят порт.

1. В меню «Пуск»
выберите пункт «Выполнить«;
2. В поле «Открыть» наберите команду cmd
и нажмите кнопку «ОК»;

Откроется окно командной строки, примерно такого вида:

3. Наберите команду
netstat -ano и нажмите кнопку «Ввод» (Enter)
на клавиатуре;

Результатом выполнения данной команды, должен быть список всех активных
подключений, с ip-адресами и номерами портов.

4. Теперь
в колонке «Локальный адрес», находим нужный нам порт и записываем его
идентификатор в колонке «PID»;

Например порт номер 80, его
идентификатор 440.

5. Снова открываем меню «Пучк» и
выбираем пункт «Выполнить«;
6. В поле «Открыть» вводим команду  taskmgr и нажимаем кнопку
«ОК»;
7. В окне «Диспетчер задач Windows» переходим
на вкладку «Процессы«;
8. В главном меню открываем пункт «Вид» и выбираем пункт «Выбрать
столбцы…
«;
9. В окне «Выбор столбцов» находим пункт «Идентиф. процесса (PID)»
и ставим рядом с ним галочку;
10. Нажимаем кнопку «ОК»;
11. Теперь в окне «Диспетчер задач Windows«,
нажимаем на заголовок столбца «PID», для сортировки
процессов по возрастанию;
12. Находим номер нашего процесса 440 и в столбце «Имя образа«, смотрим какой
процесс занимает наш порт;

В нашем случаи это
Apache.exe

Комментарий ICaR-Soft.ru (13.07.2016 10:57)


БОЛЬШОЕ спасибо!

Комментарий MYcks (24.04.2016 13:33)


Просто и понятно объяснил. Спасибо!

Комментарий Яр (16.03.2016 13:05)


Отлично! Спасибо, очень помогло

Комментарий лИнивый (11.11.2015 17:18)


Ок спасибо! То что надо.

Комментарий zguzga (21.10.2015 17:56)


+1 большое спасибо!

Комментарий Alexstrigin (07.09.2015 20:55)


VELESTOR (26.08.2015 00:32)

Спасибо тебе добрый человек!!!

Комментарий VELESTOR (26.08.2015 00:32)


Открываем 80-тый порт в Windows 7, 8, 10 за 5 секунд, нужно всего лишь перекинуть http.sys c IPv4 на IPv6.
Инструкция http://velestor.com/q/port80/
У меня Windows 10, помог только этот способ!

Все для свадьбы

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

Mateen Ulhaq's user avatar

Mateen Ulhaq

23.8k18 gold badges95 silver badges132 bronze badges

asked Sep 7, 2008 at 6:26

readonly's user avatar

readonlyreadonly

341k107 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.6k34 gold badges116 silver badges200 bronze badges

answered May 18, 2014 at 5:02

bcorso's user avatar

bcorsobcorso

45.2k10 gold badges63 silver badges75 bronze badges

10

For Windows:

netstat -aon | find /i "listening"

xash's user avatar

xash

3,70210 silver badges22 bronze badges

answered Sep 7, 2008 at 6:32

aku's user avatar

akuaku

122k32 gold badges172 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,7015 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,0693 gold badges28 silver badges44 bronze badges

answered Jan 24, 2018 at 3:50

Ram Sharma's user avatar

Ram SharmaRam Sharma

2,4471 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,3601 gold badge11 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,24412 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

53.8k29 gold badges201 silver badges196 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

bahrep's user avatar

bahrepbahrep

29.7k12 gold badges103 silver badges150 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,33814 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

7331 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,9312 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

1,0261 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

wzso's user avatar

wzsowzso

3,3574 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

190k57 gold badges311 silver badges299 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

7,1202 gold badges61 silver badges102 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,2943 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

102k15 gold badges175 silver badges252 bronze badges

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,6296 silver badges14 bronze badges

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

108k96 gold badges384 silver badges482 bronze badges

3

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,1222 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

6971 gold badge7 silver badges18 bronze badges

2

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

3083 silver badges7 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

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

При работе в Unix-системах мне частенько приходится определять, какой процесс занимает порт, например, чтобы остановить его и запустить на нём другой процесс. Поэтому я решил написать эту небольшую статью, чтоб каждый, прочитавший её, мог узнать, каким процессом занят порт в Ubuntu, CentOS или другой ОС из семейства Linux.

Как же вычислить, какие запущенные процессы соотносятся с занятыми портами? Как определить, что за процесс открыл udp-порт 2222, tcp-порт 7777 и т.п.? Получить подобную информацию мы можем нижеперечисленными методами:

netstat
утилита командной строки, показывающая сетевые подключения, таблицы маршрутизации и некоторую статистику сетевых интерфейсов;
fuser
утилита командной строки для идентификации процессов с помощью файлов или сокетов;
lsof
утилита командной строки, отображающая информацию об используемых процессами файлах и самих процессах в UNIX-системе;
/proc/$pid/
в ОС Linux /proc для каждого запущенного процесса содержит директорию (включая процессы ядра) в /proc/$PID с информацией об этом процессе, в том числе и название процесса, открывшего порт.

Использование вышеперечисленных способов может потребовать права супер-пользователя.

Теперь давайте рассмотрим каждый из этих способов по отдельности.

Пример использования netstat

Введём в командную строку команду:

$ netstat -tulpn


Получим примерно такой результат:

Proto Recv-Q Send-Q Local Address           Foreign Address         State       PID/Program name    
tcp        0      0 0.0.0.0:10843           0.0.0.0:*               LISTEN      7023/node           
tcp        0      0 127.0.0.1:4942          0.0.0.0:*               LISTEN      3413/java           
...


Из вывода видно, что 4942-й порт был открыт Java-приложением с PID’ом 3413. Проверить это можно через /proc:

$ ls -l /proc/3413/exe


Примерный результат выполнения команды:

lrwxrwxrwx. 1 user user 0 Nov 10 20:31 /proc/3413/exe -> /opt/jdk1.8.0_60/bin/java


При необходимости получения информации по конкретному порту (например, 80-му, используемого обычно для HTTP) вместо отображения всей таблицы можно grep-ануть результат:

$ netstat -tulpn | grep ':80 '


Результат будет примерно такой:

tcp        0      0 0.0.0.0:80              0.0.0.0:*               LISTEN      1607/apache2


Пример использования fuser

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

$ fuser 5050/tcp


И получим результат:

5050/tcp:             3813


Аналогичным образом, как мы делали выше, можно посмотреть процесс в его директории /proc/$PID, в которой можно найти много интересной дополнительной информации о процессе, такую как рабочая директория процесса, владелец процесса и т.д., но это выходит за рамки этой статьи.

Пример использования lsof

При использовании lsof введите команду по одному из шаблонов:

lsof -i :$portNumber
lsof -i tcp:$portNumber
lsof -i udp:$portNumber


Пример реального использования:

lsof -i :80 | grep LISTEN


Результат выполнения:

apache2   2123     root    3u  IPv4   6472      0t0  TCP *:www (LISTEN)
apache2   2124 www-data    3u  IPv4   6472      0t0  TCP *:www (LISTEN)
apache2   2125 www-data    3u  IPv4   6472      0t0  TCP *:www (LISTEN)
apache2   2126 www-data    3u  IPv4   6472      0t0  TCP *:www (LISTEN)


После этого мы можем получить более полную информацию о процессах с PID’ами 2123, 2124 и т.д..

$ ps aux | grep 2124


На выходе получим примерно следующее:

www-data 2124 0.0 0.0 36927 4991 ? S 10:20 0:00 /usr/sbin/apache2 -k start


Получить информацию о процессе также можно следующим проверенным способом:

$ ps -eo pid,user,group,args,etime,lstart | grep '2727'


2727 www-data www-data /usr/sbin/apache2 -k start     14:27:33 Mon Nov 30 21:21:28 2015


В этом выводе можно выделить следующие параметры:

  • 2727 — PID;
  • www-date — имя пользователя владельца;
  • www-date — название группы;
  • /usr/sbin/apache2 -k start — название команды с аргументами;
  • 14:27:33 — время работы процесса в формате [[дд-]чч:]мм:сс;
  • Mon Nov 30 21:21:28 2015 — время старта процесса.

Надеюсь, у меня получилось доступно объяснить, как определить процесс по порту в Linux-системах, и теперь у вас ни один порт не останется неопознанным!

До новых статей!

Программы, способные соединяться с интернетом при подключении к сети используют так называемые порты — цифровые адреса сетевых устройств. Иногда при тонкой настройке программ или устройств возникает необходимость узнать, какое приложение занимает тот или иной порт, например с целью освободить его для другой программы. В Windows сделать это очень просто. Основных вариантов два: с помощью обычной командной строки и с помощью сторонних утилит.

В командной строке

Для отображения текущих соединений TCP/IP в Windows используется штатная консольная утилита netstat. Она может принимать более 10 параметров, но для того чтобы узнать какой порт занят каким процессом, вполне хватит трех: -a, -o и –n. Для начала необходимо получить список всех текущих соединений. От имени администратора откройте консоль CMD и выполните эту команду:

netstat –aon

netstat

Данные будут выведены в пять колонок: имя, локальный адрес, внешний адрес, состояние и идентификатор процесса (PID). Отыщите нужный вам порт и посмотрите, с каким PID он связан. Теперь откройте Диспетчер задач, переключитесь на вкладку «Процессы» (в Windows 7) или «Подробности» (в Windows 8.1) и найдите в списке этот PID. А найдя его, вы идентифицируете и процесс.

Процессы

Примечание: если в Диспетчере задач у вас не отображается ИД процесса, включите его через меню «Вид» -> «Выбрать столбцы».

В утилите CurPorts

Второй способ более прост, но для определения занимающего порт процесса вам понадобится сторонняя утилита CurPorts. Она бесплатна, проста и не требует установки.

CurPorts

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

CurPorts

Утилита CurPorts доступна для скачивания на сайте разработчика www.nirsoft.net. Там же можно скачать и файл для её русификации.

Загрузка…

Понравилась статья? Поделить с друзьями:
  • Как найти сколько страниц в журнале
  • Как найти токи в ветвях методом кирхгофа
  • Как составить воркшоп
  • Расширение не загружено как исправить
  • Как найти телефон по геолокации андроид включенный