views:

196

answers:

1

I'm working with socket in python, and being in development stage I need to kill and restart my program frequently.

The issue is that once killed my python script, I've to wait long time to be able to rebind the listen socket. Here's a snippet to reproduce the problem:

#!/usr/bin/env python3                                                          

import socket

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((socket.gethostname(), 4321))
try:
    s.listen(5)
    while True:
        (a, b) = s.accept()
        print(a.recv(1000))
except KeyboardInterrupt:
    print("Closing")
    s.shutdown(socket.SHUT_RDWR)
    s.close()

Hitting C-z runs the except code, calling shutdown and close functions, but I'm not able to restart my program until the socket timeout (GNU/Linux environment).

How can I avoid this?

+3  A: 

I'm not sure how to do it in Python, but you want to set the SO_REUSEADDR socket option.

Richard Pennington
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) s.bind((socket.gethostname(), 4321))That works. Thanks guy!
Enrico Carlesso