fast and secure web hosting. from a simple website to a highly visited e-shop  

How to find the IPs connecting to my server?

The following command displays a list of the IPs that are connected to our server ignoring the STATE of the connection (CLOSE_WAIT, ESTABLISHED, etc)
netstat -tn 2>/dev/null
-t flag tells netstat to display only TCP connections and -n flag tells netstat command not to resolve IPs to hostnames While stderr (2) redirection (>) throws at "garbage" (/dev/null) means that we just don't want possible errors to break our cute output we are trying to make. At this point we have all usable information, but it is a little difficult to use, we will try to come to a more clear and handy format. Piping (|) to grep, we can keep only the IPs that are connecting to port 80 of our webserver.
netstat -tn 2>/dev/null | grep ":80 "
It would be also nice to keep only the 5th column right?
netstat -tn 2>/dev/null | grep ":80 " | awk '{print $5}'
Maybe the trickiest part here is that we only want IPs to be displayed so we use: cut -d: -f1 Where: -d tells cut to use the immediate following character as a delimiter. -f tells how many fields to output, in our case we just need one.
netstat -tn 2>/dev/null | grep ":80 " | awk '{print $5}' | cut -d: -f1
Then using sort, we are sorting our list, using -c we are counting unique occurrences and then we can display in descending order with sort -nr (numeric και reverse). It's in our judgement to use head to check only the first 10 results.
netstat -tn 2>/dev/null | grep ":80 " | awk '{print $5}' | cut -d: -f1 | sort | uniq -c | sort -nr | head
Of course, changing the port only in grep, ie to 25, we are able to see if someone is abusing our mail server or in a VPS hosting environment the tracking of a spammer can be a little bit easier. Also we can use a specific connection state in grep that we are interested in, count connections per process (using parameter -p in netstat). Essentially it's about few commands that combined together they become a very useful tool for an system & network administrator.