trying sockets

Steve Holden sholden at
Tue Oct 2 16:30:38 CEST 2001

"Uwe Schmitt" <uwe at> wrote ...
> Hi,
> i'm just playing with the socket module: i'd like to send
> a "GET/HTTP" request to a webserver and record the answer
> of the server. so i wrote
>    from socket import *
>    snd=socket(AF_INET,SOCK_STREAM)
>    snd.connect(("",80))
>    print snd.getsockname()
>    lstn=socket(AF_INET,SOCK_STREAM)
>    lstn.bind(snd.getsockname())
>    snd.send("GET / HTTP/1.0 ")
>    lsten.listen(1)
>    conn,addr=lstn.accept()
>    print conn.recv(1024)
>    lstn.close()
>    snd.close()
> but i get the following output:
>    ('', 1662)
>    Traceback (most recent call last):
>       File "", line 8, in ?
>         lsten.bind(snd.getsockname())
>    socket.error: (98, 'Address already in use')
> so: what did i do wrong ???
Sockets are a little difficult to understand when you are just getting
started, but the good news is they are quite easy to deal with once you
understand the concepts involved. Gordon McMilllan has produced some very
useful tutorial material available in several places, including

and I would encourage you to read that for an overview of the processes

The main problem is that you should use the same socket to send and receive
when you have established a connection to the server. Server structures are
rather different, you listen() on a socket, and when accept() returns it
provides you with a newly-created socket that you can use to communicate
with the connected client.

So you are actually making things much more difficult than they need to be!
Here's a revised program:

from socket import *
# Note that this is bad practice unless you KNOW
# the module is specifically designed for it.
# import socket
# snd = socket.socket(...)
# would be a more typical sequence.

print snd.getsockname()

snd.send("GET / HTTP/1.0\r\n\r\n")
print snd.recv(1024)


There you go. When I run this it returns the following output:

<TITLE>302 Found</TITLE>
The document has moved <A
<ADDRESS>Apache/1.3.12 Server at Port 80</ADDRESS>

This actually looks reasonable. Of course, there's lots more to do...

As another poster pointed out, Python does include libraries for client-side
and server-side HTTP, but they can be a little opaque at times. There's
nothing wrong with trying to hack up some simple scripts yourself, although
you will find there is much to be learned from the library code. Good luck!


More information about the Python-list mailing list