This is really a follow-up to my post about a Python oauth2 BaseHTTPServer conflicting with SABNzbd+.
Basically, I have the following little script (which is used to create a local server listening for Google API oauth2 credentials):
import socket
import BaseHTTPServer
from oauth2client.tools import ClientRedirectServer, ClientRedirectHandler
port_number = 0
host_name = 'localhost'
for port_number in range(8080,10000):
try:
httpd = ClientRedirectServer((host_name, port_number),
ClientRedirectHandler)
except socket.error, e:
print "socket error: " + str(e)
pass
else:
print "The server is running on: port " + str(port_number)
print "and host_name " + host_name
httpd.serve_forever()
break
On OS X, if I run this script twice, I get the expected results:
socket error: [Errno 48] Address already in use
The server is running on: port 8081
and host_name localhost
However, running the same script from different cmd windows in Win7, I can happily run 3 or 4 servers on the same port (8080) without throwing a socket error:
C:\>netstat -abn | Findstr 8080
TCP 127.0.0.1:8080 0.0.0.0:0 LISTENING
TCP 127.0.0.1:8080 0.0.0.0:0 LISTENING
Per Ned Deily’s comment, Windows doesn’t treat multiple sockets the same way other OS’s may.
I think that the correct way to do this in windows (and the way that worked for me, and thus the answer I’ll choose) is to bind the port to 0 and let Windows handle it by itself. You can then get the used port number back with
sock.getsockname()[1].For anyone else trying to do this with the Google oauth2client.tools, see the code I went with below: