Socket question: arbitrary port

Robert W. Bill rbill at digisprings.com
Thu Jul 27 14:36:44 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?
> 
> Any help would be appreaciated!
> Thanks!
> 

My understanding is (assuming you're talking AF_INET) is that
it requires a port for the bind call for a server socket and a destination
port to connect to for a client socket. So you would have to
identinfy the port for those calls. 
i.e.-
import socket

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
#you need a connect or bind to do something with it
s.bind('127.0.0.1', 80) #second num is port
s.connect('www.python.org', 80) #same here- need destination port num

the lazy persons's method to pick the first available port (warning: bad
idea/example):

portNum = 1
while 1:
    try: 
	s.bind('127.0.0.1', portNum)
	break
    except socket.error, why:
	# could analyze why here 
	portNum = portNum + 1

--replace the above s.bind with s.connect('someplace', portNum), and you
have a great way to stir trouble :)

Without details I might have missed the point, but the generalized answer 
is you provide a port for connect/bind in your program by some means
rather than python picking it.

-robert




More information about the Python-list mailing list