首頁·終端機命令

netstat

網路

用法

netstat -tulpn | netstat -an

查看 socket 和路由表的老辦法;在 Linux 上這活已交給 ss,而且常常根本沒裝,macOS 雖然保留了它,卻無法說出 socket 屬於哪個行程,那要靠 lsof。

常用選項

選項含義
-tulpnThe Linux combination: TCP, UDP, listening, with process, numeric.
-anAll sockets, numeric. The form that also works on macOS/BSD.
-rRouting table; add -n to keep it numeric.
-iPer-interface packet and error counters.
-sProtocol statistics, useful for retransmit counts.
-v -p tcpmacOS/BSD: verbose, one protocol. macOS cannot map sockets to processes at all.

範例

sudo netstat -tulpn

Listening ports with their processes (Linux, needs root for -p).

netstat -an | grep LISTEN

The listening list on macOS, where -p means something else.

netstat -rn

The routing table on either platform.

連不上的時候,這些能把範圍縮小——是名稱解析不了、沒有路由,還是連接埠被擋。

怎麼看

  • 方括號 [ ] 表示這部分可以不寫。
  • 省略號 … 表示可以寫多個。
  • 選項區分大小寫——有些命令裡 -r 和 -R 不是一回事。

常見問題

Q. netstat 是做什麼的?

查看 socket 和路由表的老辦法;在 Linux 上這活已交給 ss,而且常常根本沒裝,macOS 雖然保留了它,卻無法說出 socket 屬於哪個行程,那要靠 lsof。

Q. 怎麼寫?

netstat -tulpn | netstat -an —— 方括號表示可以省略的部分。

Q. 值得記的選項有幾個?

這裡列了 6 個,完整列表在 man netstat。這條命令屬於網路。

相關命令

man 手冊: man netstat