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:16

This works in Mavericks (OSX 10.9.2).

sudo lsof -nP -iTCP:$PORT -sTCP:LISTEN
查看更多
一个人的天荒地老
3楼-- · 2019-01-01 14:18

Since Yosemite (10.10), up to Mojave (10.14), every version of macOS supports this:

sudo lsof -iTCP -sTCP:LISTEN -n -P
查看更多
与君花间醉酒
4楼-- · 2019-01-01 14:18

I am a Linux guy. In Linux it is extremely easy with netstat -ltpn or any combination of those letters. But in Mac OS X netstat -an | grep LISTEN is the most humane. Others are very ugly and very difficult to remember when troubleshooting.

查看更多
低头抚发
5楼-- · 2019-01-01 14:19

This is a good way on macOS High Sierra:

netstat -an |grep -i listen
查看更多
皆成旧梦
6楼-- · 2019-01-01 14:20

I made a small script to see not only who is listening where but also to display established connections and to which countries. Works on OSX Siera

#!/bin/bash
printf "\nchecking established connections\n\n"
for i in $(sudo lsof -i -n -P | grep TCP | grep ESTABLISHED | grep -v IPv6 | 
grep -v 127.0.0.1 | cut -d ">" -f2 | cut -d " " -f1 | cut -d ":" -f1); do
    printf "$i : " & curl freegeoip.net/xml/$i -s -S | grep CountryName | 
cut -d ">" -f2 | cut -d"<" -f1
done

printf "\ndisplaying listening ports\n\n"

sudo lsof -i -n -P | grep TCP | grep LISTEN | cut -d " " -f 1,32-35

#EOF

Sample output
checking established connections

107.178.244.155 : United States
17.188.136.186 : United States
17.252.76.19 : United States
17.252.76.19 : United States
17.188.136.186 : United States
5.45.62.118 : Netherlands
40.101.42.66 : Ireland
151.101.1.69 : United States
173.194.69.188 : United States
104.25.170.11 : United States
5.45.62.49 : Netherlands
198.252.206.25 : United States
151.101.1.69 : United States
34.198.53.220 : United States
198.252.206.25 : United States
151.101.129.69 : United States
91.225.248.133 : Ireland
216.58.212.234 : United States

displaying listening ports

mysqld TCP *:3306 (LISTEN)
com.avast TCP 127.0.0.1:12080 (LISTEN)
com.avast TCP [::1]:12080 (LISTEN)
com.avast TCP 127.0.0.1:12110 (LISTEN)
com.avast TCP [::1]:12110 (LISTEN)
com.avast TCP 127.0.0.1:12143 (LISTEN)
com.avast TCP [::1]:12143 (LISTEN)
com.avast TCP 127.0.0.1:12995 (LISTEN)
com.avast [::1]:12995 (LISTEN)
com.avast 127.0.0.1:12993 (LISTEN)
com.avast [::1]:12993 (LISTEN)
Google TCP 127.0.0.1:34013 (LISTEN)

This may be useful to check if you are connected to north-korea! ;-)

查看更多
君临天下
7楼-- · 2019-01-01 14:20

Inspired by user Brent Self:

lsof -i 4 -a | grep LISTEN

查看更多
登录 后发表回答