Who is listening on a given TCP port on Mac OS X?

2019-01-01 14:10发布

On Linux, I can use netstat -pntl | grep $PORT or fuser -n tcp $PORT to find out which process (PID) is listening on the specified TCP port. How do I get the same information on Mac OS X?

16条回答
残风、尘缘若梦
2楼-- · 2019-01-01 14:29

On Snow Leopard (OS X 10.6.8), running 'man lsof' yields:

lsof -i 4 -a

(actual manual entry is 'lsof -i 4 -a -p 1234')

The previous answers didn't work on Snow Leopard, but I was trying to use 'netstat -nlp' until I saw the use of 'lsof' in the answer by pts.

查看更多
姐姐魅力值爆表
3楼-- · 2019-01-01 14:34

On the latest macOS version you can use this command:

lsof -nP -i4TCP:$PORT | grep LISTEN

If you find it hard to remember then maybe you should create a bash function and export it with a friendlier name like so

vi ~/.bash_profile

and then add the following lines to that file and save it.

function listening_on() {
    lsof -nP -i4TCP:"$1" | grep LISTEN
}

Now you can type listening_on 80 in your Terminal and see which process is listening on port 80.

查看更多
不再属于我。
4楼-- · 2019-01-01 14:36

You can also use:

sudo lsof -i -n -P | grep TCP

This works in Mavericks.

查看更多
何处买醉
5楼-- · 2019-01-01 14:36

For the LISTEN, ESTABLISHED and CLOSED ports

sudo lsof -n -i -P | grep -i TCP

For the LISTEN ports only

sudo lsof -n -i -P | grep -i LISTEN

For a specific LISTEN port, ex: port 80

sudo lsof -n -i -P | grep -i ":80 (LISTEN)"

Or if you just want a compact summary [no service/apps described]

netstat -an | grep 'LISTEN '

Explaining the items used:

-n suppress the host name

-i for IPv4 and IPv6 protocols

-P omit port names

-a [over netstat] for all sockets

-n [over netstat] don't resolve names

Tested on High Sierra 10.13.3

BTW, the last syntax netstat works on linux too

查看更多
登录 后发表回答