详谈Linux netstat命令(高级面试必备)

2019-09-23 09:07:23于丽

列出所有 udp 端口 netstat -au

# netstat -au
 Active Internet connections (servers and established)
 Proto Recv-Q Send-Q Local Address      Foreign Address     State
 udp    0   0 *:bootpc        *:*
 udp    0   0 *:49119         *:*
 udp    0   0 *:mdns         *:*

2. 列出所有处于监听状态的 Sockets

只显示监听端口 netstat -l

# netstat -l
 Active Internet connections (only servers)
 Proto Recv-Q Send-Q Local Address      Foreign Address     State
 tcp    0   0 localhost:ipp      *:*           LISTEN
 tcp6    0   0 localhost:ipp      [::]:*         LISTEN
 udp    0   0 *:49119         *:*

只列出所有监听 tcp 端口 netstat -lt

# netstat -lt
 Active Internet connections (only servers)
 Proto Recv-Q Send-Q Local Address      Foreign Address     State
 tcp    0   0 localhost:30037     *:*           LISTEN
 tcp    0   0 *:smtp         *:*           LISTEN
 tcp6    0   0 localhost:ipp      [::]:*         LISTEN

只列出所有监听 udp 端口 netstat -lu

# netstat -lu
 Active Internet connections (only servers)
 Proto Recv-Q Send-Q Local Address      Foreign Address     State
 udp    0   0 *:49119         *:*
 udp    0   0 *:mdns         *:*

只列出所有监听 UNIX 端口 netstat -lx

# netstat -lx
 Active UNIX domain sockets (only servers)
 Proto RefCnt Flags    Type    State     I-Node  Path
 unix 2   [ ACC ]   STREAM   LISTENING   6294   private/maildrop
 unix 2   [ ACC ]   STREAM   LISTENING   6203   public/cleanup
 unix 2   [ ACC ]   STREAM   LISTENING   6302   private/ifmail
 unix 2   [ ACC ]   STREAM   LISTENING   6306   private/bsmtp

3. 显示每个协议的统计信息

显示所有端口的统计信息 netstat -s

# netstat -s
 Ip:
 11150 total packets received
 1 with invalid addresses
 0 forwarded
 0 incoming packets discarded
 11149 incoming packets delivered
 11635 requests sent out
 Icmp:
 0 ICMP messages received
 0 input ICMP message failed.
 Tcp:
 582 active connections openings
 2 failed connection attempts
 25 connection resets received
 Udp:
 1183 packets received
 4 packets to unknown port received.
 .....

显示 TCP 或 UDP 端口的统计信息 netstat -st 或 -su

# netstat -st
# netstat -su

4. 在 netstat 输出中显示 PID 和进程名称 netstat -p

netstat -p 可以与其它开关一起使用,就可以添加 “PID/进程名称” 到 netstat 输出中,这样 debugging 的时候可以很方便的发现特定端口运行的程序。

# netstat -pt
 Active Internet connections (w/o servers)
 Proto Recv-Q Send-Q Local Address      Foreign Address     State    PID/Program name
 tcp    1   0 ramesh-laptop.loc:47212 192.168.185.75:www    CLOSE_WAIT 2109/firefox
 tcp    0   0 ramesh-laptop.loc:52750 lax:www ESTABLISHED 2109/firefox