Thursday, January 17, 2013

How to determine open TCP/IP files/sockets of a Linux/Unix Process

Using lsof, a standard linux tool. 

Let's assume we want to see the open TCPV4 sockets ( normal, remote connections ) for a linux process. 
We assume we know the PID. 

Relevant lsof options : 

-i4  ( displays TCPV4 sockets ) 
-p  ( displays files for a particular process ) 
-a  ( uses AND to filter the results. Be careful. If you do not use this then lsof  uses OR in the filters and you will get the wrong answer ) 

OK lets try it out and then refine. 

let's look at the CUPS Daemon for something nice and easy 


[root]# ps -ef|grep cups
root      5160     1  0  2012 ?        00:00:46 cupsd

OK  so now we have something to look at , pid 5160 

[root]# lsof -a -i4 -p 5160
COMMAND  PID USER   FD   TYPE DEVICE SIZE NODE NAME
cupsd   5160 root    4u  IPv4  14303       TCP localhost.localdomain:ipp (LISTEN)
cupsd   5160 root    7u  IPv4  14307       UDP *:ipp


OK so we are seeing hostnames and service names. 

We use -n to convert hostnames to IP addresses


[root]# lsof -a -n -i4 -p 5160
COMMAND  PID USER   FD   TYPE DEVICE SIZE NODE NAME
cupsd   5160 root    4u  IPv4  14303       TCP 127.0.0.1:ipp (LISTEN)
cupsd   5160 root    7u  IPv4  14307       UDP *:ipp

And we use -P to convert network service names to numbers , which for most Oracle applications is much more relevant. 


[root]# lsof -a -n -P -i4 -p 5160
COMMAND  PID USER   FD   TYPE DEVICE SIZE NODE NAME
cupsd   5160 root    4u  IPv4  14303       TCP 127.0.0.1:631 (LISTEN)
cupsd   5160 root    7u  IPv4  14307       UDP *:631

So we can see that CUPS is listening locally on port 631. 

Regards, 
Chris Slattery. 





No comments: