[Python-Dev] socket.try_reuse_address()

Trent Nelson tnelson at onresolve.com
Wed Apr 30 19:40:37 CEST 2008


> > Giampaolo Rodola' wrote:
> > > Maybe it would be better considering Windows CE systems too:
> > >
> > > - if os.name == 'nt'
> > > + if os.name in ('nt', 'ce')
> > >
> > Cygwin? I don't know how Unix-like it is.
>
> Yeah, that's a fair point, it's the behaviour of the
> underlying Winsock API we're targeting, so it would apply to
> Cygwin as well.  (And CE and anything else on Windows.)

....including Jython and IronPython -- which all exhibit the same undesirable behaviour on Windows when SO_REUSEADDR is set against a TCP/IP socket.  Updated patch below.  Assuming there are no objections, I'd like to clean this up and commit over the weekend, once I've updated the various parts of the stdlib currently using SO_REUSEADDR, as well as affected documentation.

Index: socket.py
===================================================================
--- socket.py   (revision 62509)
+++ socket.py   (working copy)
@@ -143,8 +143,18 @@
     'sendall', 'setblocking',
     'settimeout', 'gettimeout', 'shutdown')

+# Attempt to determine if we're running on Windows, irrespective of our Python
+# incarnation.  We need to know this so that we *don't* set the SO_REUSEADDR
+# against TCP/IP sockets in socket.try_reuse_addr().  Note that IronPython is
+# covered below as it sets os.name to 'nt'.
 if os.name == "nt":
     _socketmethods = _socketmethods + ('ioctl',)
+    _is_windows = True
+elif os.name == 'java':
+    from java.lang import System
+    _is_windows = 'windows' in System.getProperty('os.name').lower()
+elif os.name == 'posix' and sys.platform == 'cygwin':
+    _is_windows = True

 if sys.platform == "riscos":
     _socketmethods = _socketmethods + ('sleeptaskw',)
@@ -197,6 +207,13 @@
         Return a new socket object connected to the same system resource."""
         return _socketobject(_sock=self._sock)

+    def try_reuse_address(self):
+        if not (_is_windows and self._sock.type != SOCK_DGRAM):
+            try:
+                self._sock.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
+            except socket.error:
+                pass
+
     def makefile(self, mode='r', bufsize=-1):
         """makefile([mode[, bufsize]]) -> file object



        Trent.


More information about the Python-Dev mailing list