I need to bind to an address/interface and port without waiting for the TIME_WAIT
(or whatever determines a socket's timeout). The code below works great on Ubuntu, but the sockopt socket.SO_EXCLUSIVEADDRUSE
doesn't seem to work on Windows 7, 8, or 8.1. I get the error saying I can only bind once. But why doesn't it work? I've read that windows should not use SO_REUSEADDR
so I don't. Also, I've read that this scenario could be caused by not closing the socket, but I make sure I close it.
import socket
import pdb
HOST = '127.0.0.1'
PORT = 5004
BIND = ('127.0.0.1', 9890)
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
print('Using EXCLUSIVEADDRUSE')
s.setsockopt(socket.SOL_SOCKET, socket.SO_EXCLUSIVEADDRUSE, 1)
except:
print('Using REUSEADDR')
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind(BIND)
s.connect((HOST, PORT))
s.close()
error:
socket.error: [Errno 10048] Only one usage of each socket address
(protocol/network address/port) is normally permitted
PS
This is to simply bandaide a problem I'm having where my client keeps losing connection with my server (which keeps track of clients using their (host, port)
. A real fix will come later (hopefully soon). Also, this question is about a client connection not a listening server.