Centos – How to know the process name which is opening a tcp port

centoslsofnetstatnetworkingtcp

I have two linux servers. Let's say they are C and S.
C is client of S

On my S machine, I type.

$ netstat -an | grep ESTABLISHED
tcp 0 0 192.168.1.220:3306 C:57010 ESTABLISHED

Then I can know C is connecting now.
In the C machine, I'd also like to know the process name which is opening the port 57010 and connecting the S server.
How can I do that? Of course I have root permission of C.

Best Answer

One way is to say lsof -i:57010 -sTCP:ESTABLISHED. This walks the kernel's open file handle table looking for processes with an established TCP connection using that port. (Network sockets are file handles on *ix type systems.) You'd use -sTCP:LISTEN on the server side to filter out only the listener socket instead.

Because of the way lsof works, it can only see processes your user owns unless you run it as root. It's also fairly inefficient, since a typical *ix system has a lot of file handles open at any given time. The netstat method given in another answer is faster and usually has lower access requirements.

The lsof method has one great advantage, however: not all *ix type OSes have a netstat flag for including the process name in the output, whereas lsof has been ported to every *ix type OS you're likely to use. OS X's netstat is this way, for example. It has a -p option, but it does something different from netstat -p on Linux.

For an uncommon port number like the one in your question, you can typically get away without adding lsof's -s flag, because a given machine is unlikely to have programs both connecting to the port and listening on it. It can be helpful to add it with port numbers like HTTP's 80, where it is likely you'll have multiple programs using that port at once.

It's fortunate that the -s flag is optional in many situations, because that usage only works with lsof version 4.81 and newer. In older versions, -s meant something else entirely! That's a 2008 vintage change, but it can still bite unexpectedly. RHEL 5 ships with lsof 4.78, for example.

Related Question