python code for simple daemon

import socket
import time
import signal

s.bind(('', 20201))

def stop(*a, **k):
    global work
    work = False

signal.signal(signal.SIGINT, stop)
signal.signal(signal.SIGTERM, stop)

work = True

while work:


It's bound to port 20201, so i can be sure that only one instance is running. If i try to run another instance, i see error, just as planned:

Address already in use

But i can't find a way to locate pid or any other info abount bound port

netstat -a | grep 20201 gives nothig

lsof -i TCP | grep 20201 gives nothing

ss | grep 20201 gives nothing

Is there any way to find process for bound, but not listening port?

  • Perhaps fuser 20201/tcp ? Don't you need to specify a protocol family when doing socket()? (I'm not so familiar with python.) – wurtel Oct 31 '14 at 14:46
  • Doublecheck that 20201 isn't in /etc/services since netstat/lsof/ss may be using the port's name, not number. – user2267 Oct 31 '14 at 19:13
  • Or use netstat -an so the port numbers will be numeric. – Barmar Oct 31 '14 at 20:28
  • @wurtel Python presumably provides reasonable defaults for all the socket parameters. – Barmar Oct 31 '14 at 20:29
  • I was able to reproduce this using netstat -an, so it does seem like this is a problem. – Barmar Oct 31 '14 at 20:32

I tried lsof -p <pid of python process>. It includes the line:

python  1834 barmar    3u  sock    0,6       0t0 70994705 can't identify protocol

So while you can't find the process that has a specific port bound this way, you could use

lsof | grep "can't identify protocol"

to find all processes that have ports bound but not connected or listening. If there are multiple, you can probably figure out which is likely to be using the port you care about.

Note that there are other ways a socket can get into this state. When I ran the above command, it listed a long-idle mysql process. This is because mysqld closes idle client connections after a timeout. mysql detects this when it tries to send a new query, and reconnects at that time. But until then, the client process still has the old socket open, but there's no TCP connection associated with it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.