- Find the Process Listening to Port on Mac OS X
- Step-by-Step
- Find the Process ID (PID)
- Find the Process ID (PID) Using lsof
- Find the Process ID (PID) Using netstat
- Find the Process Name
- Other Useful Commands
- How to Kill or Stop the Process by PID
- The lsof Command
- The Funk Blog
- The profound rantings of the one like Tom Atkinson… and now art gallery and shop.
- netstat macos Show Listening Ports TCP Sockets with Grep
- Show Server Port and Process ID in Netstat Mac
- About Netstat
- Pipe netstat Into Grep To Remove Junk From The End
- The Little Snitch Command — Who’s phoning home?
- Linux Equivalent
- Кто прослушивает данный TCP-порт в Mac OS X?
- 17 ответов
- Найти сервер, работающий на порту 80
- Образец вывода
- Параметры
- How to Use the Netstat Command on Mac
- See open ports and those in use
- What to Know
- How to Run Netstat
- Netstat Flags and Options
- Syntax
- Useful Flags
- Netstat Examples
- Accessing Netstat Through Network Utility
- Supplementing Netstat With Lsof
- Lsof Flags and Options
- lsof Examples
- Other Networking Commands
Find the Process Listening to Port on Mac OS X
Step-by-Step
To find the process that is listening to a port on Mac OS X, we’ll use the lsof command to find the process ID (PID), and the ps command to show the name.
Find the Process ID (PID)
There are two different ways we can use to find the process that is listening to a port on Mac OS X.
Find the Process ID (PID) Using lsof
Using the lsof command we can find the process ID (PID) for a specific port that is in a LISTEN state. In a terminal type the following and replace the “
” with our port number.
This generates output that looks like this:
In the output above the PID (process ID) is the second value, in this example output the process ID (PID) is “63851”. This command will also print out the port number, which is 9999 in the above output example.
Find the Process ID (PID) Using netstat
Using the nestat command we can find the process ID (PID) for a specific port. In a terminal type the following and replace the “
” with our port number.
This generates output that looks like this:
In the output above the PID (process ID) is the ninth value (the fourth value from the end), in this example output the process ID (PID) is “63851”. This command will also print out the port number, which is 9999 in the above output example.
Find the Process Name
We can now use the process status command ps to display the process name for the process ID (PID).
This generates output that looks like this:
In the output above the process name is the last value “the-process.” Now we know the name of the process that is listening to the port. The reason as to why the grep command is listed twice is to avoid displaying the process ID (PID) for the grep command itself.
Other Useful Commands
How to Kill or Stop the Process by PID
You can kill the process by process ID (PID) using the kill command. Replace “
” with the process ID from lsof or netstat.
The lsof Command
The lsof command lists open files. Network sockets count as files, so each open network socket, either listening or actively in use is listed by lsof. In addtion you can run the man lsof command to display all the different options for lsof.
lsof can take a very long time to execute, so I suggest that you use -n (inhibits the conversion of network numbers to host names for network files) and -P (inhibits the conversion of port numbers to port names for network files) to speed it up.
Источник
The Funk Blog
The profound rantings of the one like Tom Atkinson… and now art gallery and shop.
netstat macos Show Listening Ports TCP Sockets with Grep
Show only servers — that is ports that are listening waiting for an inbound connection:
netstat -Waltn | grep LISTEN
Show Server Port and Process ID in Netstat Mac
Instead of netstat you need to use LSOF (lists open files and sockets), piped into grep which will only shows lines with LISTEN in them:
sudo lsof -Pnl +M -i | grep LISTEN
Use -i4 for ip4 and -i6 for ip6. -i seems to work for all internet traffic. Handy for tracking down what program is running a server on your machine.
About Netstat
If you’re looking to list open network ports the Mac equivalent to the linux command netstat -Walntpc might be what you’re after. You are not alone, I get about 6,000 unique visitors per year here! Realtime list of all open connections and listening sockets: watch netstat -Walnt (No DNS much faster) watch netstat -Walt (with DNS lookups) The beauty of this command is that it gets you past that over long list of (non-internet surely?) unix sockets and kexts, why Apple put this into netstat I have no idea, perhaps the blame is with Darwin BSD kernel. But it should be more like Linux netstat in my opinion! That’s because I can even see the process names and get continuous updates my adding pc with
Pipe netstat Into Grep To Remove Junk From The End
Listening socket / server processes ports macOS quickly: netstat -Waltn | grep tcp Every internet port fast with no DNS lookups: netstat -Waltn | grep -E «(tcp|udp)(4|6)» Like above but with DNS lookups but takes literally forever up to minutes: netstat -Walt | grep -E «(tcp|udp)(4|6)»
The Little Snitch Command — Who’s phoning home?
How to use LSOF to discover which app or process is listening to which ports: lsof -Pnl +M -i -cmd | grep -E «LISTEN|TCP|UDP» I prefer to use -n to speed up the listing of netstat results by turning off DNS lookups ip to name resolution. The l is used to also show ipv6. To show all internet connections, whether ipv4 or ipv6, tcp or udp, listening, connected or closing — the lot: netstat -Waltn | grep p[46] Show only TCP connections: netstat -anp tcp To see which apps have listening sockets open: sudo lsof -n -P | grep LISTEN Some other good linux ones here: http://www.commandlinefu.com/commands/matching/netstat/bmV0c3RhdA==/sort-by-votes
Linux Equivalent
This one is good for checking ssh tunnels: sudo netstat -tulpn
Posted by tomachi on January 12th, 2016 filed in Mac, Unix
Источник
Кто прослушивает данный TCP-порт в Mac OS X?
В Linux я могу использовать netstat -pntl | grep $PORT или fuser -n tcp $PORT , чтобы узнать, какой процесс (PID) прослушивает указанный порт TCP. Как мне получить ту же информацию в Mac OS X?
17 ответов
В macOS Big Sur и более поздних версиях используйте эту команду:
Или просто увидеть IPv4:
В более старых версиях используйте одну из следующих форм:
Замените $PORT номером порта или списком номеров портов, разделенных запятыми.
Добавьте sudo (после пробела), если вам нужна информация о портах ниже # 1024.
Флаг -n предназначен для отображения IP-адресов вместо имен хостов. Это заставляет команду выполняться намного быстрее, потому что поиск DNS для получения имен хостов может быть медленным (несколько секунд или минут для многих хостов).
Флаг -P предназначен для отображения необработанных номеров портов вместо разрешенных имен, таких как http , ftp или более эзотерических имен сервисов, таких как dpserve , socalia .
Смотрите комментарии для получения дополнительных опций.
Для полноты картины, потому что часто используются вместе:
Чтобы убить PID:
Начиная со Snow Leopard, до Catalina и Big Sur , каждая версия macOS поддерживает следующее:
sudo lsof -iTCP -sTCP:LISTEN -n -P
Лично я получил эту простую функцию в своем
Затем команда listening выдаст вам список процессов, прослушивающих какой-либо порт, и listening smth найдет в нем какой-то шаблон.
Имея это, довольно легко спросить о конкретном процессе, например listening dropbox или порт, например listening 22 .
Команда lsof имеет несколько специализированных параметров для запроса порта, протокола, процесса и т. Д., Но лично я нашел вышеупомянутую функцию гораздо более удобной, поскольку мне не нужно запоминать все эти низкоуровневые параметры. lsof — довольно мощный инструмент, но, к сожалению, не очень удобный в использовании.
Вы также можете использовать:
Это работает в Mavericks.
Обновление, январь 2016 г.
По-настоящему удивленный, никто не предложил:
Чтобы получить основную необходимую информацию. Например, проверка порта 1337:
Другие варианты, в зависимости от обстоятельств:
Вы можете легко использовать это для извлечения самого PID. Например:
Что также эквивалентно (в результате) этой команде:
Для полноты картины, поскольку часто используются вместе:
Чтобы убить PID:
Или как один вкладыш:
Это работает в Mavericks (OSX 10.9.2).
Для портов LISTEN, ESTABLISHED и CLOSED
Только для портов LISTEN
Для конкретного порта LISTEN, например: порт 80
Или, если вам просто нужна краткая сводка [службы / приложения не описаны], воспользуйтесь NETSTAT. Хорошая сторона здесь в том, что sudo не требуется
Объяснение используемых предметов:
-n подавить имя хоста
-i для протоколов IPv4 и IPv6
-P не указывать имена портов
-a [over netstat] для всех сокетов
-n [over netstat] не разрешать имена, показывать сетевые адреса в виде чисел
Проверено на High Sierra 10.13.3 и Mojave 10.14.3.
- последний синтаксис netstat также работает в Linux
В OS X вы можете использовать параметр -v для netstat, чтобы указать связанный pid.
Вывод будет выглядеть так:
PID — это число перед последним столбцом, в данном случае 3105.
В последней версии macOS вы можете использовать эту команду:
Если вам трудно запомнить, то, возможно, вам стоит создать функцию bash и экспортировать ее с более понятным именем, например так
А затем добавьте в этот файл следующие строки и сохраните его.
Теперь вы можете ввести listening_on 80 в свой терминал и посмотреть, какой процесс прослушивает порт 80 .
В Snow Leopard (OS X 10.6.8) запуск man lsof дает:
(фактический ручной ввод — ‘lsof -i 4 -a -p 1234’)
Предыдущие ответы не работали на Snow Leopard, но я пытался использовать netstat -nlp, пока не увидел использование lsof в ответе pts.
Я парень Linux. В Linux это очень просто с netstat -ltpn или любой комбинацией этих букв. Но в Mac OS X netstat -an | grep LISTEN самый гуманный. Другие очень уродливы, и их трудно запомнить при поиске и устранении неисправностей.
Это показывает, кто чем занимается. Удалите -n, чтобы увидеть имена хостов (немного медленнее).
Это сделало то, что мне было нужно.
Я сделал небольшой скрипт, чтобы не только видеть, кто где слушает, но и отображать установленные связи и с какими странами. Работает на OSX Siera
Это может быть полезно, чтобы проверить, подключены ли вы к Северной Корее! 😉
Вдохновленный пользователем Брент Селф:
lsof -i 4 -a | grep LISTEN
Для macOS я использую две команды вместе, чтобы показать информацию о процессах, прослушивающих машину, и о процессе, подключающемся к удаленным серверам. Другими словами, чтобы проверить порты прослушивания и текущие (TCP) соединения на хосте, вы можете использовать две следующие команды вместе
Думал, что добавлю свой вклад, надеюсь, это может кому-то помочь.
Это хороший способ для macOS High Sierra:
В macOS есть простой способ получить идентификатор процесса, который прослушивает определенный порт, с помощью netstat . В этом примере выполняется поиск процесса, обслуживающего контент через порт 80:
Найти сервер, работающий на порту 80
Образец вывода
Второй из последнего столбца — это PID. Выше это 715 .
Параметры
-a — показать все порты, в том числе используемые серверами
-n — показывать числа, не искать имена. Это делает команду на много быстрее
-v — подробный вывод, чтобы получить идентификаторы процессов
-w — поисковые слова. В противном случае команда вернет информацию для портов 8000 и 8001, а не только «80».
LISTEN — давать информацию только для портов в режиме LISTEN, т.е. серверов
Источник
How to Use the Netstat Command on Mac
See open ports and those in use
What to Know
- To run netstat and see detailed data about your Mac’s network, open a new Terminal window, type netstat, and press Enter.
- Limit netstat’s output with flags and options. To see netstat’s available options, type man netstat at the command prompt.
- Use the lsof command to make up for netstat’s missing or limited functionality, including displaying any files currently open in any apps.
This article explains how to run the netstat Terminal command in macOS so that you can see detailed information about your Mac’s network communications, including the ways your Mac is talking to the outside world, across all ports and all applications.
How to Run Netstat
Learning how to use netstat can help you understand the connections your computer is making and why. The netstat command is available on Macs by default. You don’t need to download or install it.
Go to Finder > Go > Utilities.
Double-click Terminal.
In the new Terminal window, type netstat and press Return (or Enter) to execute the command.
A huge amount of text will begin scrolling on your screen. If you don’t use any of the available flags (see below), netstat reports the active network connections on your Mac. Considering the number of functions a modern network device performs, you can expect the list to be lengthy. A standard report can run over 1,000 lines.
Netstat Flags and Options
Filtering netstat’s output is essential to understanding what’s happening on your Mac’s active ports. Netstat’s built-in flags allow you to set options, limiting the command’s scope.
To see all netstat’s available options, type man netstat at the command prompt to reveal netstat’s man (short for «manual») page. You can also view an online version of netstat’s man page.
Syntax
It’s important to note that netstat on macOS doesn’t work the same way as netstat on Windows and Linux. Using flags or syntax from those implementations of netstat may not result in the expected behavior.
To add flags and options to netstat on macOS, use the following syntax:
netstat [-AabdgiLlmnqrRsSvWx] [-c queue] [-f address_family] [-I interface] [-p protocol] [-w wait]
If the above shorthand looks completely incomprehensible, learn how to read command syntax.
Useful Flags
Here are some of the most commonly used flags:
- -a includes server ports in netstat’s output, which are not included in the default output.
- -g displays information associated with multicast connections.
- -Iinterface provides packet data for the specified interface. All available interfaces can be viewed with the -i flag, but en0 is typically the default outgoing network interface. (Note the lowercase letter.)
- -n suppresses the label of remote addresses with names. This speeds up netstat’s output while eliminating only limited information.
- -pprotocol lists traffic associated with a specific networking protocol. The full list of protocols is available at /etc/protocols, but the most important ones are udp and tcp.
- -r displays the routing table, showing how packets are routed around the network.
- -s shows the network statistics for all protocols, whether or not the protocols are active.
- -v increases verbosity, specifically by adding a column showing the process ID (PID) associated with each open port.
Netstat Examples
Consider these examples:
netstat -apv TCP
This command returns only TCP connections on your Mac, including open ports and active ports. It also uses verbose output, listing the PIDs associated with each connection.
netstat -a | grep -i «listen»
This combination of netstat and grep reveals open ports, which are ports that are listening for a message. The pipe character | sends the output of one command to another command. Here, the output of netstat pipes to grep, letting you search it for the keyword «listen» and find the results.
Accessing Netstat Through Network Utility
You also can access some of netstat’s functionality through the Network Utility app, which is included in macOS versions up to Catalina (it’s not included in Big Sur).
To get to Network Utility, type Network Utility into Spotlight Search to launch the app, then select the Netstat tab to access the graphical interface.
Options within Network Utility are more limited than those available through the command line. Each of the four radio button selections runs a preset netstat command and displays the output.
The netstat commands for each radio button are as follows:
- Display routing table information runs netstat -r.
- Display comprehensive network statistics for each protocol runs netstat -s.
- Display multicast information runs netstat -g.
- Display the state of all current socket connections runs netstat.
Supplementing Netstat With Lsof
The macOS implementation of netstat doesn’t include much of the functionality users expect and need. Although it has its uses, netstat isn’t as useful on macOS as it is on Windows. A different command, lsof, replaces much of the missing functionality.
Lsof displays files currently open in apps. You can also use it to inspect app-associated open ports. Run lsof -i to see the list of applications communicating over the internet. This is typically the goal when using netstat on Windows machines; however, the only meaningful way to accomplish that task on macOS is not with netstat, but with lsof.
Lsof Flags and Options
Displaying every open file or internet connection is typically verbose. That’s why lsof comes with flags for restricting results with specific criteria. The most important ones are below.
For information on more flags and technical explanations of each, check out lsof’s man page or run man lsof at a Terminal prompt.
- -i displays open network connections and the name of the process that is using the connection. Adding a 4, as in -i4, displays only IPv4 connections. Adding a 6 instead (-i6) displays only IPv6 connections.
- The -i flag also can be expanded to specify further details. -iTCP or -iUDP returns only TCP and UDP connections. -iTCP:25 returns only TCP connections on port 25. A range of ports can be specified with a dash, as it -iTCP:25-50.
- Using -i@1.2.3.4 returns only connections to the IPv4 address 1.2.3.4. IPv6 addresses can be specified in the same fashion. The @ precursor can also be used to specify hostnames in the same way, but both remote IP addresses and hostnames cannot be used simultaneously.
- -s typically forces lsof to display file size. But when paired with the -i flag, -s works differently. Instead, it allows the user to specify the protocol and status for the command to return.
- -p restricts lsof to a particular process ID (PID). Multiple PIDs can be set by using commons, such as -p 123,456,789. Process IDs can also be excluded with a ^, as in 123,^456, which would specifically exclude PID 456.
- -P disables the conversion of port numbers to port names, speeding up output.
- -n disables the conversion of network numbers to hostnames. When used with -P above, it can significantly speed up lsof’s output.
- —uuser only returns commands owned by the named user.
lsof Examples
Here are a few ways to use lsof.
lsof -nP -iTCP@lsof.itap:513
This complex-looking command lists the TCP connections with the hostname lsof.itap and the port 513. It also runs lsof without connecting names to IP addresses and ports, making the command run noticeably faster.
lsof -iTCP -sTCP:LISTEN
This command returns every TCP connection with the status LISTEN, revealing the open TCP ports on the Mac. It also lists the processes associated with those open ports. This is a significant upgrade over netstat, which lists PIDs at most.
sudo lsof -i -u^$(whoami)
Other Networking Commands
Other Terminal networking commands that might be of interest in examining your network include arp, ping, and ipconfig.
Источник