[Linux/Mac] 找出占用 port 的 process
今天在找 Sublime Text plugin 的一個問題,
錯誤訊息如下,看起來像是有人占了 port 50962,
導致 Anaconda 這個 plugin 無法去用那個 port:
ERROR:root:Traceback (most recent call last): File "/Users/testuser/Library/Application Support/Sublime Text 3/Packages/Anaconda/anaconda_lib/worker.py", line 191, in start self.client = AsynClient(self.available_port) File "/Users/testuser/Library/Application Support/Sublime Text 3/Packages/Anaconda/anaconda_lib/jsonclient.py", line 36, in __init__ EventHandler.__init__(self, (host, port)) File "/Users/testuser/Library/Application Support/Sublime Text 3/Packages/Anaconda/anaconda_lib/ioloop.py", line 105, in __init__ self.sock.connect(address) ConnectionRefusedError: [Errno 61] Connection refused Something is using the port 50962 in your system ERROR:Anaconda.anaconda_lib.worker:Something is using the port 50962 in your system Registering handler with address ('localhost', 50962)
要如何去查出來哪個 process 使用了某個 port 呢?
在 Linux 上通常可以使用 netstat -lnp 就可以把開啟 port 的 process 也列出來,例如:
(用 sudo 是因為用 root 帳號才能將所有 process 的 name 秀出來,
不然只能看到屬於自己的 process name 囉)
testuser@localhost ~ $ sudo netstat -l -n -p Active Internet connections (only servers) Proto Local Address Foreign Address State PID/Program name tcp 192.168.122.1:53 0.0.0.0:* LISTEN 2543/dnsmasq tcp 0.0.0.0:22 0.0.0.0:* LISTEN 2107/sshd tcp 127.0.0.1:631 0.0.0.0:* LISTEN 1904/cupsd tcp 127.0.0.1:25 0.0.0.0:* LISTEN 2227/master tcp 0.0.0.0:17500 0.0.0.0:* LISTEN 3599/dropbox tcp 0.0.0.0:24800 0.0.0.0:* LISTEN 3674/synergys tcp 0.0.0.0:111 0.0.0.0:* LISTEN 1795/rpcbind tcp 0.0.0.0:58000 0.0.0.0:* LISTEN 1867/rpc.statd tcp :::22 :::* LISTEN 2107/sshd tcp ::1:631 :::* LISTEN 1904/cupsd tcp ::1:25 :::* LISTEN 2227/master
netstat 在 Mac 上也有,可是不支援 -p 選項…
在 stackoverflow 上查到了可以用 lsof -i 加上 grep 來輔助找出來,
像下面可以查到是 pid 1336 的 Python 正在 listen port 50962:
testuser@localhost ~ $ lsof -i | grep 50962 plugin_ho 1332 testuser 38u IPv4 0xd9abee310a06d78b 0t0 TCP localhost:51825->localhost:50962 (ESTABLISHED) Python 1336 testuser 4u IPv4 0xd9abee310757debb 0t0 TCP localhost:50962 (LISTEN) Python 1336 testuser 7u IPv4 0xd9abee310a09a05b 0t0 TCP localhost:50962->localhost:51825 (ESTABLISHED)
詳細的 process 資訊可以再用 ps 來查:
testuser@localhost ~ $ ps aux | egrep -w 1336 | grep -v grep
testuser 1336 0.0 0.1 2475388 16856 ?? S 3:58 0:00.67 python -B /Users/testuser/Library/Application Support/Sublime Text 3/Packages/Anaconda/anaconda_lib/../anaconda_server/jsonserver.py -p MyProject 50962 -e /tmp/MyProject 1332
(本頁面已被瀏覽過 2,466 次)