Oct 072009

Netstat is an extremely useful Linux command line tool that allows you to check which service is connecting to a port on your machine. It is very useful to analyze what’s going on on your machine when you are facing or trying to to prevent an attack on it. You can find information such as how many connection are being made on a port, which IP addresses these connections originate from, and much more. Netstat ships with most distributions of Linux so it should already be installed on yours.

Launch a shell terminal on your machine and run the following command:

# netstat -ant
Active Internet connections (servers and established)
Proto Recv-Q Send-Q Local Address Foreign Address State
tcp 0 0 ::ffff: ::ffff: TIME_WAIT
tcp 0 0 ::ffff: ::ffff: TIME_WAIT
tcp 0 0 ::ffff: ::ffff: TIME_WAIT

The output will most likely be very long. I’ve just given a snapshot of the output above. As you can see in the data above there is a connection made from to my server’s port 80 using the TCP protocol and the connection in the a state of TIME_WAIT. The out put that you get for your server will have information about all the ports on your machine, not just port 80.

The first thing you realize is that an output this big is not of too much use. So let’s organize it a bit. Here are a few tricks I use to analyze the nature of the connections being made to of from my server. the first thing I do is figure out which services I want to analyze. Usually it is port 80 as that’s the default port for the web server to run on, and port 3306 which is the default port for MySQL to run on. So i use the following query to see what’s going on on port 80:

# netstat -ant | grep 80

Again I get big list of connections, smaller than the first, but still too big to grasp. So I use the “wc -l” command to count the number of lines in the output to see approximately how many connections I have on my port 80:

# netstat -ant | grep 80 | wc -l

And then I do the same for MySQL:

# netstat -ant | grep 3306 | wc -l

Now, if I want to get a complete picture of what’s going on on my server in terms of the nature of connections here’s what I do:

# netstat -ant | awk ‘{print $6}’ | sort | uniq -c | sort -n

1 established)
1 Foreign

This tells me how many connections of different types of state I have on my machine. I can run a similar command to see a complete picture of the state of all the connections made to my web server:

netstat -ant | grep 80 | awk ‘{print $6}’ | sort | uniq -c | sort -n


You can perform a lot more complex things using Netstat along with other Linux command line tools. It can be helpful to be familiar with some tricks to get this kind of information using Netstat, particularly when you are facing an attack on your server.

 Posted by at 6:01 am