The netstat Command



The netstat Command

Like curl and wget, netstat can be very useful in helping determine the source of problems. Using netstat with the -an option lists all the TCP ports on which your Linux server is listening, including all the active network connections to and from your server. This can be very helpful in determining whether slowness is due to high traffic volumes:

     [root@bigboy tmp]# netstat -an
     Active Internet connections (servers and established)
     Proto Recv-Q Send-Q Local Address      Foreign Address       State
     tcp        0      0 127.0.0.1:25       0.0.0.0:*             LISTEN
     tcp        0      0 :::80              :::*                  LISTEN
     ...
     ...
     ...
     [root@bigboy tmp]#

Most TCP connections create permanent connections. HTTP is different because the connections are shut down on their own after a predefined inactive timeout or time_wait period on the Web server. It is therefore a good idea to focus on these types of short-lived connections. You can determine the number of established and time_wait TCP connections on your server by using the netstat command filtered by the grep and egrep commands, with the number of matches being counted by the wc command, which in this case shows 14 connections:

     [root@bigboy tmp]# netstat -an | grep tcp | egrep -i \
     'established|time_wait' | wc -l
     14
     [root@bigboy tmp]#

The netstat -nr command can also be used to view your routing table. It is always good to ensure that your routes are correct and that you can ping all the gateways in your routing table. The traceroute command, which I'll discuss later, can then be used to verify that your routing table is correct by displaying the path a packet takes to get to a remote destination. If the first hop is incorrect, then your routing table needs to be examined more carefully.

     [root@bigboy tmp]# netstat -nr
     Kernel IP routing table
     Destination   Gateway        Genmask         Flags MSS Window irtt
     Iface
     172.16.68.64  172.16.69.193  255.255.255.224 UG    40  0      0     eth1
     172.16.11.96  172.16.69.193  255.255.255.224 UG    40  0      0     eth1
     172.16.68.32  172.16.69.193  255.255.255.224 UG    40  0      0     eth1
     172.16.67.0   172.16.67.135  255.255.255.224 UG    40  0      0     eth0
     172.16.69.192 0.0.0.0        255.255.255.192 U     40  0      0     eth1
     172.16.67.128 0.0.0.0        255.255.255.128 U     40  0      0     eth0
     172.160.0     172.16.67.135  255.255.0.0     UG    40  0      0     eth0
     172.16.0.0    172.16.67.131  255.240.0.0     UG    40  0      0     eth0
     127.0.0.0     0.0.0.0        255.0.0.0       U     40  0      0     lo
     0.0.0.0       172.16.69.193  0.0.0.0         UG    40  0      0     eth1
     [root@bigboy tmp]#