serious rresvport problem in python 2.2.1

Carey Evans careye at spamcop.net
Wed Aug 14 04:11:57 CEST 2002


Dan Stromberg wrote:
> I've been using a modified version of Carey Evans' rresvport function
> in a printsystem.

I'd actually forgotten writing this.  It's all coming back to me now 
though.  After a bit of tidying up, I get the version below, which works 
for me with Python 2.1.3 and 2.2.1 on Windows 2000 and Linux.

The main changes from my original version are:

* Fixing the bind() to use a two-element tuple.  Two arguments has 
always been wrong, but earlier versions of Python let it go.
* Removing the strange exception handling code.  I have no idea what I 
was thinking.

> So I got kind of interested in that '' in the bind call.  This is
> supposed to mean "localhost".  So I changed it to
> bind(('localhost',port)).

The '' actually means INADDR_ANY, or 0.0.0.0.  (Though for some reason, 
socket.INADDR_ANY is the integer 0, which doesn't work with bind.)  You 
could try using '0.0.0.0' instead of the empty string, although it 
should mean exactly the same thing.

----------------------------------------------------------------------
"""A module to allocate a socket on a reserved port.

Copyright (c) 1998, 2002 Carey Evans.

Permission to use, copy, modify, and distribute this software and its
documentation for any purpose and without fee is hereby granted,
provided that the above copyright notice appear in all copies and that
both that copyright notice and this permission notice appear in
supporting documentation."""

import socket, errno

class RResvPortError(Exception):
     def __str__(self):
         return 'No reserved ports available'

def rresvport():
     """rresvport() -> socket

Return a socket with a privileged address bound to it.  On Unix systems,
this can only be done by root.  If no reserved ports are available,
raise RResvPortError."""

     port = 1023
     s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
     while port >= 512:
         try:
             s.bind(('', port))
         except socket.error, detail:
             if detail[0] != errno.EADDRINUSE:
                 raise
         else:
             return s
         port = port - 1

     raise RResvPortError
----------------------------------------------------------------------

-- 
"Every time you misuse it's, ten kittens are KILLED."
   -- Ben Goodger




More information about the Python-list mailing list