Using NetStat to get process name from port number or IP addreess

NetStat is one of powerful Unix command line tools that is present on pretty much every machine, simple to use and yet is very powerful in the hands of advanced user. With NetStat you can debug network problems without installing any third-party software – you just need to learn a few command line parameters.

One command that I use very often is

netstat -tuapn

This command displays all connections (both incoming and outgoing) with corresponding IP addresses, port and process/PID numbers. Command parameters are

-t Show TCP connections
-u Show UDP connections
-a Show both listening and non-listening sockets.
-p Show the PID and name of the program to which each socket belongs
-n Show numerical addresses instead of trying to determine symbolic host, port or user names.

Output of this command is in the following format

Proto Recv-Q Send-Q Local Address               Foreign Address             State       PID/Program name
tcp        1      0 2401:db00:11:2a:face::43936 2401:db00:11:2a:face:0:1456 CLOSE_WAIT  14971/hhvm
tcp        0      0 2401:db00:11:2a:face::37665 2401:db00:11:2a:face:0:9100 ESTABLISHED -
tcp        1      0 ::1:20845                   ::1:9099                    CLOSE_WAIT  14333/hhvm
udp        0      0      *                               -
udp        0      0       *                               -

You can easily find program responsible for specific connection by running following command (just replace 20413 with PID number you get from netstat output)

[sergey ~] ps -p 20413 -o comm,args=ARGS
python          /home/sergeyma/Enthought/Canopy_64bit/System/bin/python -c from IPython.kernel.zmq.kernelapp

If you want to find all connections to specific IP address you can use

netstat -tuapn | grep

To find all connections pointing to specific port run

netstat -tuapn | grep :123

To find all connections from specific program first you need to get PID of process you are interested in (replace python with process name) and then run netstat

ps aux | grep python | grep -v grep
#Find PID of the process in the second column
netstat -tuapn | grep $PID #Replace 20413 with process number from previous step

Netstat is very versatile program that is very useful in multiple scenarios. I highly recommend to use it when debugging network issues or finding process responsible for specific port or communication with specific IP address.

This entry was posted in linux, productivity, tools. Bookmark the permalink.