Search code examples
pythontcpcross-platformpid

In python is there a cross-platform way of determining what process is listening to a given port?


In linux, I can use lsof -i as in the following function:

def FindProcessUsingPort(portnum):
    import os
    fp = os.popen("lsof -i :%s" % portnum)
    lines = fp.readlines()
    fp.close()
    pid = None
    if len(lines) >= 2:
        pid = int(lines[1].split()[1])
    return pid

Is there a cross-platform way to figure this out?

As a relevant reference, once I know the process id, the psutil library is very nice and lets me determine all sorts of useful process information for it in a cross-platform way. I just can't get the first part to work (finding the pid) cross-platform at the moment.


If not familiar with the lsof -i switch, the output looks like below (after launching a python process that opens a TCP socket listening on port 1234):

$ lsof -i :1234
COMMAND   PID USER   FD   TYPE  DEVICE SIZE/OFF NODE NAME
python  22380 russ   15u  IPv4 4015476      0t0  TCP *:1234 (LISTEN)

Solution

  • No, this is not built into python.