1

I'm using DreamHost as a hosting-provider for my server.py .If I run my code locally, the setsockopt function succesfully sets the parameter SOCKET_REUSEADDR to True and I can effectively reuse the port. But when I run server.py on the hosting, I get the error '[Errno 98] Address in use'

Running `ps aux | grep python' and manually closing processes using kill -9 PID gives me the possibility to reuse the port in the beginning. But doesen't that mean that 'socket.setsockopt' doesen't work ?

server.py

host = 'Dreamhost_IP'
port = 33000
server_socket = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
server_socket.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1)
server_socket.bind((host,port))

.
.
.
.
.

if __name__=="__main__":
    server_socket.listen(5)
    print('waitin for connections')
    accept_thread = threading.Thread(target = accept_connections)
    accept_thread.start()
    accept_thread.join()
    server_socket.close()

I'm expecting to be able to reuse the desired port by overriding the wait time with SO_REUSEADDR. If I use '127.0.0.1' as 'host' and 33000 as 'port', I can successfully rerun the server on that port.
Nikola Stoilov
  • 85
  • 1
  • 10

1 Answers1

1

SO_REUSEADDR doesn't let you bind two things to the same port at once. Its primary function is to bypass the waiting period after a socket shuts down. If you want to bind two things at once, you need to use something stronger: SO_REUSEPORT.

  • I've been reading documentations and examples until now on that, but still after changing `SO_REUSEADDR` to `SO_REUSEPORT`, I get the same error message : `server_socket.bind((host,port)) OSError: [Errno 98] Address already in use` – Nikola Stoilov Jun 13 '19 at 02:15
  • @NikolaStoilov Hmm. Any better luck setting both flags at once? – Joseph Sible-Reinstate Monica Jun 13 '19 at 02:16
  • 1
    I was able to make it work by killing running python processes (i guess some had REUSEADDR flag set to true in the memory and had to be flushed ?) and freshly start the server with `REUSEPORT` flag . Thanks for the help, Joseph, really appreciate it ! : ) – Nikola Stoilov Jun 13 '19 at 02:37
  • @NikolaStoilov If my answer solved your problem, please accept it with the checkmark button. – Joseph Sible-Reinstate Monica Jun 13 '19 at 02:38
  • Although running the server on port 33000 for e.g, i can connect multiple clients and communicate inbetween. But after restarting the server on that port, after the first connection has been established, i can't connect any more clients. It simply just doesent connect. Killing the process and restarting the script fixes the problem, but how can I avoid to kill the process ? – Nikola Stoilov Jun 13 '19 at 02:54
  • @NikolaStoilov If "killing the process" does something that "restarting the server" doesn't, that means that the server isn't really shutting down all the way. – Joseph Sible-Reinstate Monica Jun 13 '19 at 02:58