← Back to blog

Netstat – What's happening in your network

Netstat – What's happening in your network
May 3, 2018by Michal Niec
Tools

Following our initial tools post on /proc we have some hints on how to get the most out of Netstat. Still to come over the following weeks – Jmap and Gprof. If we had a thumbs up button to subscribe I'd say hit it!!

Let's dive into netstat in this post. We would like to verify to which MySQL hosts we are connected. We want to get their DNS names. netstat is a good tool to do this. Its most popular snippet on the Internet, which shows all the data, is netstat -tulnap. Let's check how it helps with our problem.

We know that our MySQL database works over TCP protocol and we use standard 3306 port. So we could start with:

netstat -tunap | grep 3306

In theory, we get what we wanted. List of IPs which use 3306 port. The problem is solved at this stage. However, we can improve our solution:

  • -u – it tells netstat to show UDP connections, we want only TCP connections so -t stays as is (it's TCP equivalent), -u can be removed.

  • -a shows us also listening sockets. We don't want to list them; we can remove it.

  • -p tells us which PID use this socket. Let's remove it for the sake of brevity.

So now we have

netstat -tn | grep 3306

The question is: do we want to use -n argument? We get what we wanted, but the DNS names are more verbose. This argument disables DNS resolution. Let's try to remove this argument:

netstat -t | grep 3306

We get an empty result. Why? Without the  -n argument, the ports are resolved to a bounded service name. So the output instead of

tcp        0 0 192.168.0.2:42059       192.168.0.10:3306 ESTABLISHED

is as follows

tcp        0 0 localhost:42059 my-db-hostname:mysql ESTABLISHED

Note mysql word. Our command should look like this

netstat -t | grep mysql

However, how does netstat know that port 3306 is bound by the mysql service? This mapping is defined in /etc/services file which describes most popular service-to-port mappings:

mysql           3306/tcp                # MySQL

Bonus:

Sometimes hostnames are too long, and netstat cuts the name. You can use -W flag to enable wide option which disables names truncating.

Share: