Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Invalid argument exception in socket.accept() if I restart immediately after a previous run quit

Tags:

python

sockets

I have a client server architecture written in python. Most of the time it works fine, but sometimes, after I stop the server and restart it immediately afterwards, I get the following error:

Accept failed due to : 22 Message Invalid argument, error: [Errno 22] Invalid argument

However, if I wait a few minutes and the start the same script again with no changes it works fine.

This is the loop I use on the server to accept incoming connections from clients:

try:
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.bind(('',port))
    s.listen(1)
except:
    #logError()

while True:
    try:
        conn, address = s.accept() #THIS ACCEPT FAILS SOMETIMES
        multiprocessing.Process(target=HandleConnection, args=(conn, address, messageQueue, taskQueue, IOLock, numberOfConnections, numberOfConnectionsLock,resultsDirectory)).start()
    except socket.error, msg:
      #logError()  -> this except catches the error

Does the port get blocked for some time after I run the server? If so, is there are way to query if the port is blocked and wait until it's unblocked if I want to start the server up again immediately after it just quit?

like image 852
Alexander Avatar asked Feb 13 '13 20:02

Alexander


1 Answers

You need to set SO_REUSEADDR before binding.

setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

Failing to do so may prevent the socket from binding, thus the error when accepting. You would have noticed this error if you hadn't choked exceptions in the first block.

like image 99
cnicutar Avatar answered Oct 19 '22 20:10

cnicutar