[Tutor] Python socket programming
Jeroen Vogelpoel
n.a.vogelpoel at chello.nl
Sun Apr 25 09:18:22 EDT 2004
Good day,
Recently I began to poke around a bit with python and I've stumbled upon
a problem with socket programming. It doesn't make allot of sense to me
anymore, so I hope someone around here can shed some light on this
matter. Anyways, here's the code that I have:
from socket import *
testsocket = socket( AF_INET, SOCK_STREAM )
testsocket.connect( ( "192.168.0.1", 80 ) )
testsocket.settimeout( 3 )
HTTPReq = "GET / HTTP/1.1"
bytesSent = testsocket.send( HTTPReq )
print len( HTTPReq )
print bytesSent
testsocket.recv( 1024 )
testsocket.close()
The socket.settimeout() has been used to stop the code from blocking
indefinitely, which would otherwise require me to shut down the running
process using Windows Task Manager. That also sums up the main problem,
this code doesn't actually receive anything. What is odd, though, is the
fact that socket.send() does return 14, the same value of len( HTTPReq )
so it did send something. However, if I look at the logs of the
webserver, it shows no incoming request from my IP at all, which would
explain why this script would block. What's also odd is that when I try
the socket examples given in the documentation, it works perfectly.
However, it only works as long as both the client and server are on the
local machine. I changed the host and port values of the example to my
webserver's host and port 80 and it blocked again, while it should have
come up with "HTTP/1.1 500 Bad Request", etcetera. Now I'm stuck on
this... :(
As for some nescesarry details reagarding the situation, the target host
does run a webserver which responds to request from the internal
network. Granted, it responds with a 403 code but that should not be an
issue, because it should receive something anyways. There are no odd TCP
settings or encryptions in use on the internal network either and the
socket system works nicely in various other languages, except for Python
in this case. I'm aware of some nifty specialized classes for HTTP
client use, but I intend to use sockets for something else later on so
this is mainly to learn how to work with sockets.
More information about the Tutor
mailing list