1. 概述

Linux is a powerful operating system that offers a wide range of commands for system administration, network management, and troubleshooting. Though it’s recently been deprecated in favor of nstat and ssnetstat remains a useful command for network administration.

In this tutorial, we’ll explore the netstat command and various examples to illustrate its usage.

2. 什么是 netstat?

netstat 是 “network statistics” 的缩写, is a command-line tool in Linux that offers details about network connections, routing tables, network interface stats, and multicast memberships. It’s a useful tool for network administrators and system operators to monitor and troubleshoot networking issues.

3. 安装 netstat

大部分Linux发行版中, netstat 属于 net-tools 的一部分,默认可能不会安装。

下面使用 apt-get 进行安装:

$ sudo apt-get update
$ sudo apt-get install net-tools

接下来,我们将通过一些示例来学习如何使用 netstat 命令。

4. 基础用法

Before diving into examples, let’s take a look at the basic syntax of the netstat command:

$ netstat [options]

The [options] section consists of various flags and parameters that control the output of netstat.

4.1. 显示当前活动中的连接

netstat is used for basic network administration tasks, such as displaying active connections and monitoring network traffic. 首先,我们直接执行 netstat 命令不带任何参数,显示所有活动中的网络连接:

$ netstat
Active Internet connections (w/o servers)
Proto Recv-Q Send-Q Local Address           Foreign Address         State      
tcp        0      0 kali:43502              103.21.5.62:https       ESTABLISHED
tcp        0      0 kali:44258              71.229.116.34.bc.:https ESTABLISHED
udp        0      0 kali:60450              maa05s09-in-f10.1:https ESTABLISHED
udp        0      0 kali:44156              maa03s26-in-f3.1e:https ESTABLISHED
Active UNIX domain sockets (w/o servers)
Proto RefCnt Flags       Type       State         I-Node   Path
unix  2      [ ]         STREAM                   25752    @printer-applet-lock-user-aashish
unix  3      [ ]         SEQPACKET  CONNECTED     28453    @5b613
unix  2      [ ]         DGRAM                    22161    /run/user/1000/systemd/notify

The command output displays network connections, routing tables, interface statistics, and multicast memberships. Here’s a breakdown of the output provided:

  • Proto: the protocol used (TCP or UDP)
  • Recv-Q: receive queue size (number of bytes received by the kernel but not yet read by the application)
  • Send-Q: send queue size (number of bytes not yet acknowledged by the remote host)
  • Local Address: IP address and port number of the local end of the connection
  • Foreign Address: IP address and port number of the remote end of the connection
  • State: current state of the connection

4.2. 列出所有监听端口

使用 -l 参数仅显示正在监听的端口:

$ netstat -l                     
Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address           Foreign Address         State      
tcp        0      0 0.0.0.0:7070            0.0.0.0:*               LISTEN     
tcp        0      0 localhost:38993         0.0.0.0:*               LISTEN     
udp        0      0 0.0.0.0:50001           0.0.0.0:*                          
udp        0      0 mdns.mcast.net:mdns     0.0.0.0:*                          
...
Active UNIX domain sockets (only servers)
Proto RefCnt Flags       Type       State         I-Node   Path
unix  2      [ ACC ]     STREAM     LISTENING     24008    @/tmp/.ICE-unix/1608
unix  2      [ ACC ]     STREAM     LISTENING     18159    /run/avahi-daemon/socket
unix  2      [ ACC ]     SEQPACKET  LISTENING     13833    /run/systemd/coredump
...

The command lists all the ports including UNIX domain sockets that are currently in a listening state, awaiting incoming connections. It provides valuable information for network troubleshooting and ensuring that services are up and running.

4.3. 列出所有TCP监听端口

netstat -lt 显示正在监听的TCP端口:

$ netstat -lt 
Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address           Foreign Address         State      
tcp        0      0 0.0.0.0:7070            0.0.0.0:*               LISTEN     
tcp        0      0 localhost:38993         0.0.0.0:*               LISTEN   

The -lt option in the netstat command stands for:

  • -l: shows only listening sockets, which are sockets that are waiting for incoming connections
  • -t: restricts the output to only TCP connections

4.4. 列出所有UDP监听端口

类似的,使用 -lu 仅显示正在监听的 UDP 端口:

$ netstat -lu
Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address           Foreign Address         State      
udp        0      0 0.0.0.0:50001           0.0.0.0:*                          
udp        0      0 mdns.mcast.net:mdns     0.0.0.0:*                          
udp        0      0 0.0.0.0:mdns            0.0.0.0:*                          
udp6       0      0 [::]:mdns               [::]:*                             
udp6       0      0 [::]:44147              [::]:* 

The command focuses on displaying only the UDP ports in a listening state. This is useful for identifying services that are using UDP for communication, such as DNS and DHCP.

4.5. 列出TCP端口的统计信息

Statistical information for network protocols provides metrics on connection counts, error rates, data transfer volumes, and other performance indicators. 使用 -s 参数收集特定网络协议的统计信息:

$ netstat -s                     
Ip:
    Forwarding: 1
    91240 total packets received
    1 with invalid addresses
    91087 incoming packets delivered
...
Icmp:
    2 ICMP messages received
    1 input ICMP message failed
    ICMP input histogram:
        destination unreachable: 2
IcmpMsg:
        InType3: 2
        OutType3: 21
Tcp:
    1371 active connection openings
    5 failed connection attempts
    145 connection resets received
    51 connections established
...

The command provides detailed statistics for various network protocols, including IP, ICMP, and TCP. It is particularly useful for diagnosing network performance issues and understanding the behavior of the network stack.

4.6. 列出TCP端口的统计信息

For a more specific breakdown of TCP port statistics, we’ll use the -s (statistics) and -t (TCP) flags with the netstat command:

$ netstat -st
IcmpMsg:
    OutType3: 3
Tcp:
    200 active connection openings
    0 passive connection openings
...
IpExt:
    InMcastPkts: 426
    OutMcastPkts: 1227
...

The command provides statistics for TCP protocol, such as packet counts, errors, and other pertinent information related to TCP connections.

4.7. 列出UDP端口的统计信息

Similar to listing statistics of TCP ports, the netstat -su command focuses on the statistical information related to UDP ports:

$ netstat -su
IcmpMsg:
    OutType3: 3
Udp:
    5487 packets received
    3 packets to unknown port received
...
UdpLite:
IpExt:
    InMcastPkts: 503
    OutMcastPkts: 1231
...

The command shows statistics for UDP protocol, including packet counts, errors, and other relevant details specific to UDP connections.

5. netstat 高级用法

netstat offers more advanced features for in-depth network analysis.

5.1. 显示路由信息

To display the kernel routing table, showing how network packets are routed to their destinations, let’s use the netstat -r command, where -r stands for route:

$ netstat -r                      
Kernel IP routing table
Destination     Gateway         Genmask         Flags   MSS Window  irtt Iface
default         dsldevice.lan   0.0.0.0         UG        0 0          0 wlan0
192.168.1.0     0.0.0.0         255.255.255.0   U         0 0          0 wlan0

The command output shows that all unspecified traffic goes through the gateway dsldevice.lan via wlan0, while local network traffic for 192.168.1.0 is directly connected via wlan0.

5.2. 显示详细信息

-tulpn 参数组合,显示所有连接的详细信息,包括PID(进程ID)、进程名、监听地址和监听状态

$ sudo netstat -tulpn
Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address           Foreign Address         State       PID/Program name    
tcp        0      0 127.0.0.1:46865         0.0.0.0:*               LISTEN      993/containerd      
udp        0      0 0.0.0.0:39214           0.0.0.0:*                           755/avahi-daemon: r 
udp        0      0 224.0.0.251:5353        0.0.0.0:*                           2546/chrome         
udp        0      0 0.0.0.0:5353            0.0.0.0:*                           755/avahi-daemon: r 
udp6       0      0 :::52189                :::*                                755/avahi-daemon: r 
udp6       0      0 :::5353                 :::*                                755/avahi-daemon: r 

The command output shows active listening ports and associated processes. Notable entries include container listening on TCP port 46865, avahi-daemon on UDP ports 39214 and 5353 (both IPv4 and IPv6), and chrome on UDP port 5353 for multicast.

Here’s what the -tulpn options mean:

  • -t: shows TCP connections
  • -u: shows UDP connections
  • -l: shows only listening sockets
  • -p: shows the PID and program name
  • -n: shows numerical addresses

5.3. 按端口过滤

Another usage of netstat can be for filtering the connections for a specific port, we’ll use netstat along with -an option and filter port 80 using grep:

$ netstat -an | grep :80
udp6       0      0 2400:1a00:b020:5a:56703 2404:6800:4002:805::443 ESTABLISHED
udp6       0      0 2400:1a00:b020:5a:49474 2404:6800:4002:80c::443 ESTABLISHED

The command shows two UDP IPv6 connections to port 443 from local addresses using port 80, both in an ESTABLISHED state.

The -an option in the netstat command means:

  • -a: displays all active connections and the listening ports
  • -n: shows addresses and port numbers in numerical form, rather than resolving them to hostnames and service names

5.4. 按IP地址过滤

Likewise, to filter the results by a specific IP address, we’ll use the netstat along with grep to filter a particular IP address:

$ netstat -an | grep 192.168.1.68
tcp        0      0 192.168.1.68:38142      103.18.12.112:443       ESTABLISHED
tcp        0      0 192.168.1.68:41608      103.18.12.112:443       ESTABLISHED

The command output shows two established TCP connections from the local IP address 192.168.1.68 to the remote IP address 103.18.12.112 on port 443. Furthermore, the connections use local ports 38142 and 41608, indicating active communications between the local machine and the remote server over HTTPS.

5.5. 实时监控网络连接

To monitor network connections in real-time, we can combine watch with netstat:

$ watch -n 1 netstat -an

We’ll get output that constantly updates:

Active Internet connections (servers and established)
Proto Recv-Q Send-Q Local Address           Foreign Address         State
tcp        0      0 127.0.0.1:46569         0.0.0.0:*               LISTEN
tcp        0      0 0.0.0.0:7070            0.0.0.0:*               LISTEN
tcp        0      0 192.168.1.68:39696      72.125.120.184:5228     ESTABLISHED
tcp        0      0 192.168.1.68:38432      182.64.154.145:443      ESTABLISHED

The command displays local and remote addresses along with their connection states. Moreover, the -n 1 option used with the watch command refreshes the displayed output every 1 second allowing us to see changes in network connections as they happen.

5.6. 监控网络性能

We can monitor network performance by examining interface statistics with netstat along with the -i option:

$ netstat -i
Kernel Interface table
Iface             MTU    RX-OK RX-ERR RX-DRP RX-OVR    TX-OK TX-ERR TX-DRP TX-OVR Flg
lo              65536      232      0      0 0           232      0      0      0 LRU
neweOth0         1500        0      0      0 0             0      0      0      0 BMU
wlan0            1500   545065      0      0 0        120469      0      0      0 BMRU

Let’s understand what the command shows about network interface statistics:

  • lo: loopback interface with 232 packets sent and received
  • neweOth0: unused interface (0 packets sent or received)
  • wlan0: wireless interface with 545,065 packets received and 120,469 packets sent

6. 总结

In this article, we explored the usage of netstat command with various examples.

netstat offers a suite of options for monitoring and troubleshooting network connections, including viewing active connections, listing listening ports, and displaying detailed protocol statistics. Despite being deprecated and replaced by ss, it remains widely used for both basic and advanced network analysis, providing essential insights into network status and performance for maintaining and diagnosing issues.