check for unused ports and then grab one

Brad Tilley bradtilley at usa.net
Mon Sep 13 18:59:50 EDT 2004


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
 >>>





More information about the Python-list mailing list