scaevity scaevity - 8 months ago 62
Python Question

Python server "Only one usage of each socket address is normally permitted"

I'm trying to create a very basic server in python that listens in on a port, creates a TCP connection when a client tries to connect, receives data, sends something back, then listens again (and repeats the process indefinitely). This is what I have so far:

from socket import *

serverName = "localhost"
serverPort = 4444

s = socket(AF_INET, SOCK_STREAM)
s.bind((serverName, serverPort))

print "Server is ready to receive data..."

while 1:
newConnection, client = s.accept()
msg = newConnection.recv(BUFFER_SIZE)

print msg

newConnection.send("hello world")

Sometimes this seems to work perfectly well (if I point my browser to "localhost:4444" the server prints out the HTTP GET request and the webpage print the text "hello world"). But I'm getting the following error message sporadically when I try to start the server after closing it in the last few minutes:

Traceback (most recent call last):
File "path\", line 8, in <module>
s.bind((serverName, serverPort))
File "C:\Python27\lib\", line 224, in meth
return getattr(self._sock,name)(*args)
error: [Errno 10048] Only one usage of each socket address (protocol/network address/port) is normally permitted

I'm programming in python using Windows 7. Any ideas on how to fix this?


Enable the SO_REUSEADDR socket option before calling bind(). This allows the address/port to be reused immediately instead of it being stuck in the TIME_WAIT state for several minutes, waiting for late packets to arrive.

s.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)