首页·终端命令

netstat

网络

用法

netstat -tulpn | netstat -an

查看套接字和路由表的老办法;在 Linux 上这活已交给 ss,而且常常根本没装,macOS 虽然保留了它,却无法说出套接字属于哪个进程,那要靠 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 是做什么的?

查看套接字和路由表的老办法;在 Linux 上这活已交给 ss,而且常常根本没装,macOS 虽然保留了它,却无法说出套接字属于哪个进程,那要靠 lsof。

Q. 怎么写?

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

Q. 值得记的选项有几个?

这里列了 6 个,完整列表在 man netstat。这条命令属于网络。

相关命令

man 手册: man netstat