trying sockets

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


"Uwe Schmitt" <uwe at rocksport.de> 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(("www.num.uni-sb.de",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:
>
>    ('134.96.31.42', 1662)
>    Traceback (most recent call last):
>       File "client.py", 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

    http://www.mcmillan-inc.com/sock1.html

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

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.

snd=socket(AF_INET,SOCK_STREAM)
snd.connect(("www.num.uni-sb.de",80))
print snd.getsockname()

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

snd.close()

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

<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
<HTML><HEAD>
<TITLE>302 Found</TITLE>
</HEAD><BODY>
<H1>Found</H1>
The document has moved <A
HREF="http://www.num.uni-sb.de/iam/index.php">here</A>.<P>
<HR>
<ADDRESS>Apache/1.3.12 Server at caesar.num.uni-sb.de Port 80</ADDRESS>
</BODY></HTML>

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!

regards
 Steve
--
http://www.holdenweb.com/








More information about the Python-list mailing list