Reputation: 1817
I'm making a (NAT traversal) script and I get the error below. Here on stackoverflow I have read that it's because SO_REUSEADDR only discards the TIME_WAIT on ports on which a socket has run. And it does NOT help, when you try to connect on the reused port to a same address (ip+port). (For NAT traversal you need to use the same port to know, which external port a NAT gives you).
Is there any way to connect to the same ip+port on the same port again and again?
Unfortunately, I cannot use UDP as I only have access to our apache school server running on TCP (maybe even the server is behind NAT, only has its 80 port forwarded).
simplified code (me, I don't connect to google, but to my school server):
>>> sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
>>> sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
>>> sock.bind(('',6000))
>>> sock.connect(('google.com',80))
>>> sock.shutdown(socket.SHUT_RDWR)
>>> sock.close()
>>> sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
>>> sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
>>> sock.bind(('',6000))
>>> sock.connect(('google.com',80))
Traceback (most recent call last):
File "<pyshell#64>", line 1, in <module>
sock.connect(('google.com',80))
File "C:\Python27\lib\socket.py", 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
>>>
Thanks for responses!
Upvotes: 2
Views: 2161
Reputation: 1817
There is a solution for you. It's called socket.SO_LINGER
and it does a force close of the connection by sending RST (reset) packet to the destination. It may not be delivered but nobody cares 'bout the school server. It can have some issues like the server can send things (that were delayed or the server did not receive the RST packet) and my computer would think it's from the now pending connection. But I guess it wouldn't send anything as I did a POST so I don't expect anything.
There is some material on internet on this theme e.g. http://www.serverframework.com/asynchronousevents/2011/01/time-wait-and-its-design-implications-for-protocols-and-scalable-servers.html
If I'm anywhere wrong, please, you may correct me.
Merry Christmas!
Upvotes: 0
Reputation: 614
The idea of the socket.SO_REUSEADDR to reuse the local port is good but the protection of TIME_WAIT to get unconsistent message from the previous source is there, kernel do not allow you to connect to the previous source.
Take a look to this article bind address
Upvotes: 1