Socket question: arbitrary port

Jonathan Giddy jon at bezek.dstc.monash.edu.au
Sun Jul 30 23:04:09 EDT 2000


] >On Thu, 27 Jul 2000, Jean Bergeron wrote:
] >
] >> Is it possible to connect a socket through an arbitrary port?
] >> In other words, can Python find an available port without having the
] >> programmer (or user) specify a particular port number?
] >> 

So far, the answers have focussed on whether you mean to bind a socket 
(server) or to connect a socket (client).

Assuming you mean to bind a server socket, try calling bind() with the 
port = 0.

This code will setup a listening socket on an arbitrary port:

import socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.bind(('', 0))
sock.listen(socket.SOMAXCONN)
print sock.getsockname()[1]

conn, addr = sock.accept()

Jon.



More information about the Python-list mailing list