check for unused ports and then grab one

Brad Tilley bradtilley at usa.net
Tue Sep 14 08:47:25 EDT 2004


Brad Tilley wrote:
> Cameron Laird wrote:
> 
>> In article <mailman.3268.1095108346.5135.python-list at python.org>,
>> Erik Heneryd  <erik at heneryd.com> wrote:
>>
>>> Brad Tilley wrote:
>>>
>>>> Instead of me arbitrarily assigning a high port number to a 
>>>> variable, is it possible to check for ports that are unused and then 
>>>> randomly assign one of them to a variable?
>>>
>>>
>>> No.  Trial and error until you find one.
>>
>>
>>             .
>>             .
>>             .
>> Incorrect, if I understand you both; *UNIX Network Programming*
>> has said for years that
>>   The process can let the system automatically assign   a port.  For 
>> both the Internet domain and the XNS
>>   domain, specifying a port number of 0 before calling
>>   bind() requests the system to do this.
>> While I've never tracked down an RFC that specifies this, it surely
>> exists.
> 
> 
> This works... even on winXP... thank you!
> 
> import socket
> 
> def get_server():
>     server = socket.gethostbyname(socket.gethostname())
>     return server
> 
> def get_port():
>     port = 0
>     return port
> 
> def listen(server_param, port_param):
>    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
>    s.bind((server_param, port_param))
>    s.listen(1)
>    ipaddr, port = s.getsockname()
>    print ipaddr, port
> 
> 
> -------------------------------------------------
> IDLE 1.0.3      ==== No Subprocess ====
>  >>>
> 192.168.1.100 1079
>  >>>
> 192.168.1.100 1080
>  >>>
> 192.168.1.100 1081
>  >>>
> 192.168.1.100 1082
>  >>>
> 192.168.1.100 1083
>  >>>
> 192.168.1.100 1084
>  >>>
> 
> 

Not that it matters, but this code always gets a much higher port number 
on my Linux computers:

IDLE 1.0.4
 >>> ================================ RESTART 
================================
 >>>
128.173.120.79 33205
 >>> ================================ RESTART 
================================
 >>>
128.173.120.79 33207
 >>> ================================ RESTART 
================================
 >>>
128.173.120.79 33209
 >>>



More information about the Python-list mailing list