Socket question: arbitrary port
Mitchell Morris
mmorris at mindspring.com
Thu Jul 27 20:20:58 EDT 2000
rbill at digisprings.com (Robert W. Bill) wrote in
<Pine.LNX.4.10.10007271034460.31368-100000 at localhost.localdomain>:
>
>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
>
>
Ewwwwwwww .... don't ever ever ever do that again. Bad dog! No biscuit!
Contrary to your reasoning, you only need bind *OR* connect. If you're
going to listen, you bind. If you're not going to listen, you connect. I
would swear this is in the Python distribution somewhere. [rummaging about
in the directory tree] There is an example in Lib/test/test_socket.py in
your Python distribution. An even shorter example is here:
C:\>python
Python 1.5.2 (#0, Apr 13 1999, 10:51:12) [MSC 32 bit (Intel)] on win32
Copyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam
>>> import socket
>>> s = socket.socket(socket.AF_INET, socket.SOCK_STREAM, 0)
>>> s.connect(('www.pythonlabs.com', 80))
>>> s.send('GET / HTTP/1.0\r\n\r\n')
18
>>> print s.recv(8192)
[deletia]
>>> s.close()
More information about the Python-list
mailing list