0

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.

notorious.no
  • 4,919
  • 3
  • 20
  • 34
  • Why do you need a specific port on the client side? See also [Python: Binding Socket: “Address already in use”](http://stackoverflow.com/questions/6380057/python-binding-socket-address-already-in-use) – sb9 Feb 26 '15 at 08:50
  • Thanks I've already read through that thread. My server maps clients based on host and port, then sends data to that client using that map. However the client has been going down and comming back up with a different port number, so data never gets delivered. – notorious.no Feb 26 '15 at 13:17
  • So the server initiates the connection to the client? – sb9 Feb 27 '15 at 11:20
  • no sorry i didn't mean to imply that the server initiates the connection. The client connects to the server, then the server saves the interface and port of the client. When the server receives data from another endpoint, it sends it to the client using the saved interface and port of the client. Does that make sense? – notorious.no Feb 27 '15 at 15:09

0 Answers0