One Linux command a day (43): netstat command

Keywords: Linux Operation & Maintenance

This article is an original article of Joshua 317. Please note: reprinted from Joshua 317 blog https://www.joshua317.com/article/203

One Linux command a day (43): netstat command

1, Introduction

The netstat command under Linux is used to display various network related information, such as network connection, routing table, interface statistics, masquerade connection, multicast members, etc. Netstat is a program to access network and related information in the kernel. It can provide reports on TCP connection, TCP and UDP listening, and process memory management.

On the whole, the output result of netstat can be divided into two parts: one is Active Internet connections, which is called active TCP connection, in which "Recv-Q" and "Send-Q" refer to receive queue and send queue. These numbers should generally be 0. If not, the package is piling up in the queue. This can only be seen in very few cases; The other is Active UNIX domain sockets, which is called Active UNIX domain sockets (like network sockets, but can only be used for local communication, and the performance can be doubled).

2, Format description

netstat [-acCeFghilMnNoprstuvVwx][-A<Network type>][--ip]
netstat [parameter]

usage: netstat [-vWeenNcCF] [<Af>] -r         netstat {-V|--version|-h|--help}
       netstat [-vWnNcaeol] [<Socket> ...]
       netstat { [-vWeenNac] -I[<Iface>] | [-veenNac] -i | [-cnNe] -M | -s [-6tuw] } [delay]

        -r, --route              display routing table
        -I, --interfaces=<Iface> display interface table for <Iface>
        -i, --interfaces         display interface table
        -g, --groups             display multicast group memberships
        -s, --statistics         display networking statistics (like SNMP)
        -M, --masquerade         display masqueraded connections

        -v, --verbose            be verbose
        -W, --wide               don't truncate IP addresses
        -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
        -o, --timers             display timers
        -c, --continuous         continuous listing

        -l, --listening          display listening server sockets
        -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

  <Socket>={-t|--tcp} {-u|--udp} {-U|--udplite} {-S|--sctp} {-w|--raw}
           {-x|--unix} --ax25 --ipx --netrom
  <AF>=Use '-6|-4' or '-A <af>' or '--<af>'; default: inet
  List of possible address families (which support routing):
    inet (DARPA Internet) inet6 (IPv6) ax25 (AMPR AX.25) 
    netrom (AMPR NET/ROM) ipx (Novell IPX) ddp (Appletalk DDP) 
    x25 (CCITT X.25) 

3, Option description

-a or--all Show all connections Socket. 
-A<Network type>or--<Network type> Lists the relevant addresses in the network type connection.
-c or--continuous Continuously list network status.
-C or--cache Displays the cache information configured by the router.
-e or--extend Displays other network related information.
-F or--fib Displays the route cache.
-g or--groups Displays the member list of the multi broadcast function group.
-h or--help Online help.
-i or--interfaces Displays the web interface information form.
-l or--listening Displays the name of the server under monitoring Socket. 
-M or--masquerade Show disguised network connections.
-n or--numeric Direct use IP Address, not through the domain name server.
-N or--netlink or--symbolic Displays the symbolic connection name of the network hardware peripheral.
-o or--timers Displays the timer.
-p or--programs Show in use Socket Program ID and program name.
-r or--route display Routing Table. 
-s or--statistics Display network work information statistics.
-t or--tcp display TCP The connection status of the transport protocol.
-u or--udp display UDP The connection status of the transport protocol.
-v or--verbose Displays the instruction execution process.
-V or--version Displays version information.
-w or--raw display RAW The connection status of the transport protocol.
-x or--unix Effect and assignment of this parameter"-A unix"The parameters are the same.
--ip or--inet Effect and assignment of this parameter"-A inet"The parameters are the same.

4, Command function

The netstat command can let you know the network situation of the whole Linux system.

5, Common usage

5.1 display detailed network

# netstat -a


netstat The output results of can be divided into two parts:

One is Active Internet connections,Called active TCP Connection, where"Recv-Q"and"Send-Q"Refers to the receive queue and the send queue. These numbers should generally be 0. If not, the package is piling up in the queue. This can only be seen in very few cases.

The other is Active UNIX domain sockets,Called active Unix Domain socket interface(It is the same as network socket, but it can only be used for local communication, and the performance can be doubled). 

Proto Displays the protocol used by the connection,RefCnt Indicates the process number connected to this set of interfaces,Types Displays the type of socket,State Displays the current status of the socket,Path Represents the pathname used by other processes connected to the socket.
Socket type:
-t : TCP

-u : UDP

-raw : RAW type

--unix : UNIX Domain type

--ax25 : AX25 type

--ipx : ipx type

--netrom : netrom type


Status description:
LISTEN: Listen for messages from afar TCP Connection request for port

SYN-SENT: After sending the connection request, wait for the matching connection request (if there are a large number of such status packets, check whether they have been recruited)

SYN-RECEIVED: After receiving and sending another connection request, wait for the other party to confirm the connection request (if there are a large number of such states, it is estimated that it will be rejected) flood (attacked)

ESTABLISHED: Represents an open connection

FIN-WAIT-1: Waiting for remote TCP Connection interruption request, or confirmation of previous connection interruption request

FIN-WAIT-2: From remote TCP Waiting for connection interruption request

CLOSE-WAIT: Waiting for connection interruption request from local user

CLOSING: Waiting for remote TCP Confirmation of connection interruption

LAST-ACK: Wait for the original message to be sent to the remote TCP Confirmation of connection interruption request (not a good thing, this item appears, check whether it is attacked)

TIME-WAIT: Wait long enough to ensure remote TCP Acknowledgement of received connection interruption request

CLOSED: No connection status

5.2 display current UDP connection

# netstat -nu

5.3 display current TCP connection

netstat -nt

5.3 display the use of UDP port number

# netstat -apu 
Active Internet connections (servers and established)
Proto Recv-Q Send-Q Local Address           Foreign Address         State       PID/Program name    
udp        0      0 0.0.0.0:bootpc          0.0.0.0:*                           933/dhclient        
udp        0      0 service-01:ntp          0.0.0.0:*                           663/ntpd            
udp        0      0 VM-0-15-centos:ntp      0.0.0.0:*                           663/ntpd            
udp6       0      0 service-01:ntp          [::]:*                              663/ntpd            
udp6       0      0 VM-0-15-centos:ntp      [::]:*                              663/ntpd 

5.4 display network card list

# netstat -i 
Kernel Interface table
Iface             MTU    RX-OK RX-ERR RX-DRP RX-OVR    TX-OK TX-ERR TX-DRP TX-OVR Flg
eth0             1500 125094783      0      0 0      135609023      0      0      0 BMRU
lo              65536 21298782      0      0 0      21298782      0      0      0 LRU

5.5 display multicast group relationship

# netstat -g 
IPv6/IPv4 Group Memberships
Interface       RefCnt Group
--------------- ------ ---------------------
lo              1      all-systems.mcast.net
eth0            1      all-systems.mcast.net
lo              1      ff02::1
lo              1      ff01::1
eth0            1      ff02::1:ff3a:5f30
eth0            1      ff02::1
eth0            1      ff01::1

5.6 display network statistics

# netstat -s

Ip:
    141486693 total packets received
    0 forwarded
    0 incoming packets discarded
    141486593 incoming packets delivered
    154098495 requests sent out
    48 dropped because of missing route
    82 reassemblies required
    14 packets reassembled ok
    14 fragments received ok
    82 fragments created
Icmp:
    13813314 ICMP messages received
    425 input ICMP message failed.
    InCsumErrors: 1
    ICMP input histogram:
        destination unreachable: 3239
        timeout in transit: 432
        echo requests: 13809376
        echo replies: 175
        timestamp request: 91
    13809624 ICMP messages sent
    0 ICMP messages failed
    ICMP output histogram:
        destination unreachable: 143
        echo request: 14
        echo replies: 13809376
        timestamp replies: 91
IcmpMsg:
        InType0: 175
        InType3: 3239
        InType8: 13809376
        InType11: 432
        InType13: 91
        OutType0: 13809376
        OutType3: 143
        OutType8: 14
        OutType14: 91
Tcp:
    11025992 active connections openings
    2461256 passive connection openings
    248809 failed connection attempts
    39534 connection resets received
    14 connections established
    123115503 segments received
    134149976 segments send out
    5202375 segments retransmited
    24422 bad segments received.
    302984 resets sent
    InCsumErrors: 23807
Udp:
    4252325 packets received
    143 packets to unknown port received.
    0 packet receive errors
    4252618 packets sent
    0 receive buffer errors
    0 send buffer errors
UdpLite:
TcpExt:
    288 SYN cookies sent
    1 SYN cookies received
    157837 invalid SYN cookies received
    228014 resets received for embryonic SYN_RECV sockets
    994 packets pruned from receive queue because of socket buffer overrun
    246 ICMP packets dropped because they were out-of-window
    965882 TCP sockets finished time wait in fast timer
    7253 packets rejects in established connections because of timestamp
    3912126 delayed acks sent
    522 delayed acks further delayed because of locked socket
    Quick ack mode was activated 152550 times
    3986 times the listen queue of a socket overflowed
    5811 SYNs to LISTEN sockets dropped
    984697 packets directly queued to recvmsg prequeue.
    464913 bytes directly in process context from backlog
    26707475 bytes directly received in process context from prequeue
    27708536 packet headers predicted
    5630 packets header predicted and directly queued to user
    44344525 acknowledgments not containing data payload received
    14968170 predicted acknowledgments
    153 times recovered from packet loss due to fast retransmit
    81069 times recovered from packet loss by selective acknowledgements
    918 bad SACK blocks received
    Detected reordering 1005 times using FACK
    Detected reordering 1003 times using SACK
    Detected reordering 32 times using reno fast retransmit
    Detected reordering 4401 times using time stamp
    1875 congestion windows fully recovered without slow start
    4205 congestion windows partially recovered using Hoe heuristic
    6088 congestion windows recovered without slow start by DSACK
    55385 congestion windows recovered without slow start after partial ack
    TCPLostRetransmit: 27834
    31 timeouts after reno fast retransmit
    11862 timeouts after SACK recovery
    44654 timeouts in loss state
    383435 fast retransmits
    25395 forward retransmits
    547771 retransmits in slow start
    3856050 other TCP timeouts
    TCPLossProbes: 589192
    TCPLossProbeRecovery: 284584
    30 classic Reno fast retransmits failed
    35939 SACK retransmits failed
    160352 DSACKs sent for old packets
    1155 DSACKs sent for out of order packets
    316513 DSACKs received
    4149 DSACKs for out of order packets received
    26395 connections reset due to unexpected data
    1736 connections reset due to early user close
    7726 connections aborted due to timeout
    TCPSACKDiscard: 41
    TCPDSACKIgnoredOld: 437
    TCPDSACKIgnoredNoUndo: 217313
    TCPSpuriousRTOs: 4212
    TCPSackShiftFallback: 699121
    TCPBacklogDrop: 1
    TCPReqQFullDoCookies: 288
    TCPRetransFail: 5
    TCPRcvCoalesce: 11995363
    TCPOFOQueue: 399736
    TCPOFOMerge: 1519
    TCPChallengeACK: 2475
    TCPSYNChallenge: 622
    TCPFastOpenCookieReqd: 11
    TCPSpuriousRtxHostQueues: 39326
    TCPAutoCorking: 533
    TCPFromZeroWindowAdv: 449
    TCPToZeroWindowAdv: 449
    TCPWantZeroWindowAdv: 3253
    TCPSynRetrans: 3411152
    TCPOrigDataSent: 76114506
    TCPHystartTrainDetect: 1896
    TCPHystartTrainCwnd: 74460
    TCPHystartDelayDetect: 6891
    TCPHystartDelayCwnd: 423886
    TCPACKSkippedSynRecv: 29912
    TCPACKSkippedPAWS: 1152
    TCPACKSkippedSeq: 971
    TCPACKSkippedTimeWait: 12
    TCPACKSkippedChallenge: 239
IpExt:
    InNoRoutes: 1
    InMcastPkts: 305307
    InOctets: 68437168659
    OutOctets: 92168136568
    InMcastOctets: 10991052
    InNoECTPkts: 143634491
    InECT1Pkts: 3
    InECT0Pkts: 8407
    InCEPkts: 1217

The statistics are displayed according to each protocol. If our application (such as Web browser) runs slowly or cannot display data such as Web pages, we can use this option to view the displayed information. We need to carefully check the rows of statistical data, find the wrong keywords, and then determine the problem.

5.7 display monitoring socket

# netstat -l

Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address           Foreign Address         State      
tcp        0      0 VM-0-15-centos:6666     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 0.0.0.0:https           0.0.0.0:*               LISTEN     
tcp        0      0 0.0.0.0:8000            0.0.0.0:*               LISTEN     
tcp        0      0 0.0.0.0:cslistener      0.0.0.0:*               LISTEN     
tcp6       0      0 [::]:mysql              [::]:*                  LISTEN     
udp        0      0 0.0.0.0:bootpc          0.0.0.0:*                          
udp        0      0 service-01:ntp          0.0.0.0:*                          
udp        0      0 VM-0-15-centos:ntp      0.0.0.0:*                          
udp6       0      0 service-01:ntp          [::]:*                             
udp6       0      0 VM-0-15-centos:ntp      [::]:*                             
Active UNIX domain sockets (only servers)
Proto RefCnt Flags       Type       State         I-Node   Path
unix  2      [ ACC ]     STREAM     LISTENING     13070    /var/run/lsm/ipc/simc
unix  2      [ ACC ]     STREAM     LISTENING     9486     /run/systemd/journal/stdout
unix  2      [ ACC ]     STREAM     LISTENING     12846    /run/dbus/system_bus_socket
unix  2      [ ACC ]     STREAM     LISTENING     532120   /tmp/mysql.sock
unix  2      [ ACC ]     STREAM     LISTENING     10552    /run/lvm/lvmpolld.socket
unix  2      [ ACC ]     STREAM     LISTENING     11852    /run/lvm/lvmetad.socket
unix  2      [ ACC ]     STREAM     LISTENING     13946    /var/run/lsm/ipc/sim
unix  2      [ ACC ]     STREAM     LISTENING     14462    /var/run/acpid.socket
unix  2      [ ACC ]     STREAM     LISTENING     291339499 /usr/local/qcloud/YunJing/conf/ydrpc_1
unix  2      [ ACC ]     SEQPACKET  LISTENING     11925    /run/udev/control
unix  2      [ ACC ]     STREAM     LISTENING     11719    /run/systemd/private
unix  2      [ ACC ]     STREAM     LISTENING     21457    /tmp/tmux-0/default

5.8 display all established valid connections

# netstat -n

5.9 display statistics about Ethernet

# netstat -e

Used to display statistics about Ethernet. It lists the total bytes, errors, deletions, datagrams and broadcasts of datagrams transmitted. These statistics include both the number of datagrams sent and the number of datagrams received. This option can be used to count some basic network traffic

5.10 display information about routing table

# netstat -r

Destination     Gateway         Genmask         Flags   MSS Window  irtt Iface
default         gateway         0.0.0.0         UG        0 0          0 eth0
link-local      0.0.0.0         255.255.0.0     U         0 0          0 eth0
172.21.0.0      0.0.0.0         255.255.240.0   U         0 0          0 eth0

5.11 count the number of network connection states in the machine

netstat -a | awk '/^tcp/ {++S[$NF]} END {for(a in S) print a, S[a]}'

LISTEN 7
CLOSE_WAIT 314
ESTABLISHED 7
TIME_WAIT 5

5.12 take out all the States and sort them after uniq -c statistics

netstat -nat |awk '{print $6}'|sort|uniq -c

314 CLOSE_WAIT
1 established)
12 ESTABLISHED
1 FIN_WAIT2
1 Foreign
7 LISTEN
2 SYN_RECV
3 TIME_WAIT

5.13 viewing the port where the program runs

netstat -ap | grep ssh

5.14 display PID and process name in netstat output

netstat -pt

5.15 find out the process running on the specified port and find the process name according to the port number

netstat -anpt | grep '80'

The process id running on port 80 is 13548. You can find the specific application through ps command.

ps -aux | grep 13548

 

This article is an original article of Joshua 317. Please note: reprinted from Joshua 317 blog https://www.joshua317.com/article/203

Posted by ganeshasri on Mon, 29 Nov 2021 11:58:38 -0800