netstat命令使用方法以及详解

Posted aiaitie

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了netstat命令使用方法以及详解相关的知识,希望对你有一定的参考价值。

首先,使用netstat命令需要安装net-tools工具包

yum -y install net-tools

这样你就有了两个linux的常用命令,netstat以及ifconfig

 

第一部分:用法

 

1、如果查看所有的linux的socker(套接字)

[root@production-001 ~]# netstat -a
 

显示如下(我粘出了一部分),会打印出Active Internet connections (servers and established和Active UNIX domain sockets (servers and established)两段;分别是活跃的网络连接和活跃的unix套接字连接

Active Internet connections (servers and established)
Proto Recv-Q Send-Q Local Address           Foreign Address         State      
tcp        0      0 VM_0_7_cento:cslistener 0.0.0.0:*               LISTEN     
tcp        0      0 VM_0_7_centos:6379      0.0.0.0:*               LISTEN     
tcp        0      0 0.0.0.0:http            0.0.0.0:*               LISTEN     
tcp        0      0 0.0.0.0:ssh             0.0.0.0:*               LISTEN     
tcp        0      0 syt-production-00:48873 19.54.0.5:lsi-bobcat ESTABLISHED
tcp        0     36 syt-production-001:ssh  12.12.11.19:51590    ESTABLISHED
tcp6       0      0 [::]:mysql              [::]:*                  LISTEN     
udp        0      0 0.0.0.0:bootpc          0.0.0.0:*                          
udp        0      0 syt-production-001:ntp  0.0.0.0:*                          
udp        0      0 VM_0_7_centos:ntp       0.0.0.0:*                          
udp6       0      0 syt-production-001:ntp  [::]:*                             
udp6       0      0 VM_0_7_centos:ntp       [::]:*                             
Active UNIX domain sockets (servers and established)
Proto RefCnt Flags       Type       State         I-Node   Path
unix  2      [ ACC ]     STREAM     LISTENING     12048    /run/dbus/system_bus_socket
unix  3      [ ]         STREAM     CONNECTED     899033   /usr/local/yd.socket.client
unix  2      [ ACC ]     STREAM     LISTENING     14887    /var/run/lsm/ipc/sim
unix  2      [ ACC ]     STREAM     LISTENING     1267868  /opt/mysql/mysql/data/mysql.sock
unix  3      [ ]         DGRAM                    8032     /run/systemd/notify
unix  2      [ ]         DGRAM                    8034     /run/systemd/cgroups-agent
unix  2      [ ACC ]     STREAM     LISTENING     8042     /run/systemd/journal/stdout
unix  5      [ ]         DGRAM                    8045     /run/systemd/journal/socket
unix  11     [ ]         DGRAM                    8047     /dev/log
unix  2      [ ACC ]     STREAM     LISTENING     14471    /run/systemd/private
unix  2      [ ACC ]     STREAM     LISTENING     13980    /var/run/acpid.socket
unix  2      [ ACC ]     STREAM     LISTENING     899772   /usr/local/yd.socket.server
unix  2      [ ACC ]     SEQPACKET  LISTENING     14506    /run/udev/control
 

 

2、查询所有的TCP或者UDP连接

TCP连接是-t,UDP连接是-u

[root@production-001 ~]# netstat -at
 

以下可以看到Local Address段显示了主机的域名,这种情况会拖慢netstat命令的执行速度

Active Internet connections (servers and established)
Proto Recv-Q Send-Q Local Address           Foreign Address         State      
tcp        0      0 VM_0_7_cento:cslistener 0.0.0.0:*               LISTEN     
tcp        0      0 VM_0_7_centos:6379      0.0.0.0:*               LISTEN     
tcp        0      0 0.0.0.0:http            0.0.0.0:*               LISTEN     
tcp        0      0 0.0.0.0:ssh             0.0.0.0:*               LISTEN     
tcp        0      0 production-00:48873 19.54.0.5:lsi-bobcat ESTABLISHED
tcp        0     36 production-001:ssh  12.12.11.19:51590    ESTABLISHED
tcp        0      0 production-001:http dynamicip-176-215:53436 TIME_WAIT  
tcp6       0      0 [::]:mysql              [::]:*                  LISTEN
 

 

3、拒绝名称解析

[root@production-001 ~]# netstat -ant
 
Active Internet connections (servers and established)
Proto Recv-Q Send-Q Local Address           Foreign Address         State      
tcp        0      0 127.0.0.1:9000          0.0.0.0:*               LISTEN     
tcp        0      0 127.0.0.1:6379          0.0.0.0:*               LISTEN     
tcp        0      0 0.0.0.0:80              0.0.0.0:*               LISTEN     
tcp        0      0 0.0.0.0:22              0.0.0.0:*               LISTEN     
tcp        0      0 172.17.0.7:48873        169.254.0.55:5574       ESTABLISHED
tcp        0     36 172.17.0.7:22           12.12.11.19:51590    ESTABLISHED
tcp6       0      0 :::3306                 :::*                    LISTEN
 

 

4、显示服务器监听的连接(LISTEN状态的连接,可用于查询服务状态)

[root@production-001 ~]# netstat -lnt
 

可以看出我的服务器跑了php、web、数据库之类的服务

Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address           Foreign Address         State      
tcp        0      0 127.0.0.1:9000          0.0.0.0:*               LISTEN     
tcp        0      0 127.0.0.1:6379          0.0.0.0:*               LISTEN     
tcp        0      0 0.0.0.0:80              0.0.0.0:*               LISTEN     
tcp        0      0 0.0.0.0:22              0.0.0.0:*               LISTEN     
tcp6       0      0 :::3306                 :::*                    LISTEN
 

 

5、显示socket对应的进程、用户等,这也是我们最常用的两种方法

如下查询server的LISTEN状态的TCP socket

[root@production-001 ~]# netstat -lnpt
 
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:9000          0.0.0.0:*               LISTEN      11821/php-fpm: mast 
tcp        0      0 127.0.0.1:6379          0.0.0.0:*               LISTEN      2058/redis-server 1 
tcp        0      0 0.0.0.0:80              0.0.0.0:*               LISTEN      344/nginx: master p 
tcp        0      0 0.0.0.0:22              0.0.0.0:*               LISTEN      3301/sshd           
tcp6       0      0 :::3306                 :::*                    LISTEN      10668/mysqld
 

 

如下查询server的所有存在的TCP socket

[root@production-001 ~]# netstat -anpt
 
Active Internet connections (servers and established)
Proto Recv-Q Send-Q Local Address           Foreign Address         State       PID/Program name    
tcp        0      0 127.0.0.1:9000          0.0.0.0:*               LISTEN      11821/php-fpm: mast 
tcp        0      0 127.0.0.1:6379          0.0.0.0:*               LISTEN      2058/redis-server 1 
tcp        0      0 0.0.0.0:80              0.0.0.0:*               LISTEN      344/nginx: master p 
tcp        0      0 0.0.0.0:22              0.0.0.0:*               LISTEN      3301/sshd           
tcp        0      0 172.17.0.7:48873        169.254.0.55:5574       ESTABLISHED 24217/YDService     
tcp        0     36 172.17.0.7:22           12.12.11.19:51590    ESTABLISHED 19772/sshd: root@pt 
tcp6       0      0 :::3306                 :::*                    LISTEN      10668/mysqld
 

 

6、打印统计数据

[root@syt-production-001 ~]# netstat -s
 
Ip:
    4938968 total packets received
    0 forwarded
    0 incoming packets discarded
    4938957 incoming packets delivered
    4805326 requests sent out
    16 dropped because of missing route
Icmp:
    769554 ICMP messages received
    16 input ICMP message failed.
    ICMP input histogram:
        destination unreachable: 28
        timeout in transit: 1
        echo requests: 769523
        echo replies: 2
    769525 ICMP messages sent
    0 ICMP messages failed
    ICMP output histogram:
        destination unreachable: 2
        echo replies: 769523
IcmpMsg:
        InType0: 2
        InType3: 28
        InType8: 769523
        InType11: 1
        OutType0: 769523
        OutType3: 2
Tcp:
    535366 active connections openings
    6904 passive connection openings
    828 failed connection attempts
    634 connection resets received
    2 connections established
    4094321 segments received
    3971608 segments send out
    4377 segments retransmited
    8 bad segments received.
    5335 resets sent
Udp:
    142930 packets received
    2 packets to unknown port received.
    0 packet receive errors
    143872 packets sent
    0 receive buffer errors
    0 send buffer errors
UdpLite:
TcpExt:
    201 invalid SYN cookies received
    637 resets received for embryonic SYN_RECV sockets
    6606 TCP sockets finished time wait in fast timer
    900 TCP sockets finished time wait in slow timer
    888 delayed acks sent
    5 delayed acks further delayed because of locked socket
    Quick ack mode was activated 438 times
    8 SYNs to LISTEN sockets dropped
    38 packets directly queued to recvmsg prequeue.
    34 bytes directly in process context from backlog
    124 bytes directly received in process context from prequeue
    1145495 packet headers predicted
    2 packets header predicted and directly queued to user
    1666927 acknowledgments not containing data payload received
    87604 predicted acknowledgments
    2 times recovered from packet loss due to fast retransmit
    2 congestion windows fully recovered without slow start
    2172 congestion windows recovered without slow start after partial ack
    2 timeouts after reno fast retransmit
    191 timeouts in loss state
    12 fast retransmits
    42 retransmits in slow start
    4019 other TCP timeouts
    245 connections reset due to unexpected data
    60 connections reset due to early user close
    198 connections aborted due to timeout
    TCPSpuriousRTOs: 147
    TCPRcvCoalesce: 529861
    TCPOFOQueue: 348
    TCPOFOMerge: 2
    TCPChallengeACK: 14
    TCPSYNChallenge: 13
    TCPFastOpenCookieReqd: 1
    TCPSpuriousRtxHostQueues: 3
    TCPWantZeroWindowAdv: 16373
    TCPSynRetrans: 550
    TCPOrigDataSent: 1907609
    TCPHystartTrainDetect: 6
    TCPHystartTrainCwnd: 281
    TCPHystartDelayDetect: 3
    TCPHystartDelayCwnd: 288
    TCPACKSkippedSynRecv: 4
    TCPACKSkippedSeq: 1
IpExt:
    InNoRoutes: 4
    InMcastPkts: 15886
    OutMcastPkts: 14
    InOctets: 1169867332
    OutOctets: 581042663
    InMcastOctets: 572027
    OutMcastOctets: 669
    InNoECTPkts: 4969489
    InECT1Pkts: 10
    InECT0Pkts: 32
 

 

第二部分:选项解释(详情可参阅netstat --help,拿过来翻译工具走一波)

        -r, --route              display routing table /显示路由信息
        -I, --interfaces=<Iface> display interface table for <Iface> /显示某个网卡信息
        -i, --interfaces         display interface table /显示网卡信息
        -g, --groups             display multicast group memberships /显示多播组信息;什么网卡、loopback口ipv4、ipv6的,还有wlan的等等信息
        -s, --statistics         display networking statistics (like SNMP) /打印netstat各种协议类型的连接统计信息
        -M, --masquerade         display masqueraded connections /显示ip_masqueraded的连接,这里解释以下ip_masqueraded,实际是NAT实现的一种,可以使多个ip发送数据包的源ip转换为同一个ip去发送,用于伪装原本发送数据的设备的ip
        
        -v, --verbose            be verbose /打印详细信息
        -W, --wide               don‘t truncate IP addresses /不截断IP地址,避免该命令截断ip连接
        -n, --numeric            don‘t resolve names /不解析名称
        --numeric-hosts          don‘t resolve host names /不解析主机名称
        --numeric-ports          don‘t resolve port names /不解析端口名称
        --numeric-users          don‘t resolve user names /不解析用户名称
        -N, --symbolic           resolve hardware names /解析硬件名称
        -e, --extend             display other/more information /显示其他或者更多信息
        -p, --programs           display PID/Program name for sockets /打印socket连接的PID、进程名
        -o, --timers             display timers /显示计时器
        -c, --continuous         continuous listing /连续监听,会一直输出

        -l, --listening          display listening server sockets /打印LISTEN状态的连接
        -a, --all                display all sockets (default: connected) /打印所有
        -F, --fib                display Forwarding Information Base (default) /显示转发信息库,路由表(默认)
        -C, --cache              display routing cache instead of FIB /显示路由缓存
        -Z, --context            display SELinux security context for sockets /显示selinux安全上下文连接
 

 

第三部分:连接状态解析

 

通常情况下:一个正常的TCP连接,都会有三个阶段(1、TCP三次握手 2、数据传送 3、TCP四次挥手)

SYN: (同步序列编号,Synchronize Sequence Numbers)该标志仅在三次握手建立TCP连接时有效。表示一个新的TCP连接请求。

ACK: (确认编号,Acknowledgement Number)是对TCP请求的确认标志,同时提示对端系统已经成功接收所有数据。

FIN:(结束标志,finish)用来结束一个TCP回话.但对应端口仍处于开放状态,准备接收后续数据。

1)、LISTEN:首先服务端需要打开一个socket进行监听,状态为LISTEN. /* The socket is listening for incoming connections. 侦听来自远方TCP端口的连接请求 */

2)、SYN_SENT:客户端通过应用程序调用connect进行active open.于是客户端tcp发送一个SYN以请求建立一个连接.之后状态置为SYN_SENT. /*The socket is actively attempting to establish a connection. 在发送连接请求后等待匹配的连接请求 */

3)、SYN_RECV:服务端应发出ACK确认客户端的SYN,同时自己向客户端发送一个SYN. 之后状态置为SYN_RECV /* A connection request has been received from the network. 在收到和发送一个连接请求后等待对连接请求的确认 */

4)、ESTABLISHED: 代表一个打开的连接,双方可以进行或已经在数据交互了。/* The socket has an established connection. 代表一个打开的连接,数据可以传送给用户 */

5)、FIN_WAIT1:主动关闭(active close)端应用程序调用close,于是其TCP发出FIN请求主动关闭连接,之后进入FIN_WAIT1状态./* The socket is closed, and the connection is shutting down. 等待远程TCP的连接中断请求,或先前的连接中断请求的确认 */

6)、CLOSE_WAIT:被动关闭(passive close)端TCP接到FIN后,就发出ACK以回应FIN请求(它的接收也作为文件结束符传递给上层应用程序),并进入CLOSE_WAIT. /* The remote end has shut down, waiting for the socket to close. 等待从本地用户发来的连接中断请求 */

7)、FIN_WAIT2:主动关闭端接到ACK后,就进入了FIN-WAIT-2 ./* Connection is closed, and the socket is waiting for a shutdown from the remote end. 从远程TCP等待连接中断请求 */

8)、LAST_ACK:被动关闭端一段时间后,接收到文件结束符的应用程序将调用CLOSE关闭连接。这导致它的TCP也发送一个 FIN,等待对方的ACK.就进入了LAST-ACK . /* The remote end has shut down, and the socket is closed. Waiting for acknowledgement. 等待原来发向远程TCP的连接中断请求的确认 */

9)、TIME_WAIT:在主动关闭端接收到FIN后,TCP就发送ACK包,并进入TIME-WAIT状态。/* The socket is waiting after close to handle packets still in the network.等待足够的时间以确保远程TCP接收到连接中断请求的确认 */

10)、CLOSING:比较少见./* Both sockets are shut down but we still don’t have all our data sent. 等待远程TCP对连接中断的确认 */

11)、CLOSED:被动关闭端在接受到ACK包后,就进入了closed的状态。连接结束./* The socket is not being used. 没有任何连接状态 */

TIME_WAIT状态的形成只发生在主动关闭连接的一方。

主动关闭方在接收到被动关闭方的FIN请求后,发送成功给对方一个ACK后,将自己的状态由FIN_WAIT2修改为TIME_WAIT,而必须再等2倍 的MSL(Maximum Segment Lifetime,MSL是一个数据报在internetwork中能存在的时间)时间之后双方才能把状态 都改为CLOSED以关闭连接。目前RHEL里保持TIME_WAIT状态的时间为60秒。

以上是关于netstat命令使用方法以及详解的主要内容,如果未能解决你的问题,请参考以下文章

Linux netstat 命令详解

Linux netstat 命令详解

Linux netstat 命令详解

Linux netstat 命令详解

Linux运维08:netstat命令详解

netstat命令详解