Linux Tip: Finding All Connections on a Port

by Aaron Brazell on September 30, 2004

I used to do Linux tips all the time over at Ensight back in the early days when Jeremy and I were group blogging and long before he decided to sell Ensight and make national Canadian news. :)

So I’m back at it again. I’ll try to deliver some handy tricks and tips that I’ve picked up along the way in a semi-regular entry.

Tonight, let’s look at a good jumping off point if you think you are being hacked.

The lsof command is useful for discovering open files by a given process. Because Unix and Linux treat all files, devices, directories and kitchen sinks as “files”, we can use lsof to find open network connections too.

For instance, if I want to find out every current connection over Secure Shell (Port 22), I can run lsof with the -i argument and the port number.

root@server [/home/admin]# lsof -i :22
COMMAND PID USER FD TYPE DEVICE SIZE NODE NAME
sshd 6241 root 3u IPv4 5760 TCP *:ssh (LISTEN)
sshd 24719 root 4u IPv4 744723 TCP server.example.com:ssh->xxx.xxx.xxx.xxx:3915 (ESTABLISHED)
sshd 24736 admin 4u IPv4 744723 TCP server.example.com:ssh->xxx.xxx.xxx.xxx:3915 (ESTABLISHED)

*Note - some distros do not include the lsof in the path. It is typically kept in /usr/sbin but may be different by setup.

*Note 2 - the xxx.xxx.xxx.xxx corresponds to the IP of your connection or your ISP-assigned hostname.

What this output tells me is that there is a TCP connection listening with the sshd daemon on port 22, that there is a TCP connection USING the sshd daemon and logged on as root and another TCP connection utilizing the sshd daemon on port 22 using the admin username.

Since these are all me, I do not worry any further.

If you want to do further research, the process ID (PID) is available as well as the ps command.

Older post: Washington (Senators?) Comeback

Newer post: More Equal Time: Guest Bloggers Wanted