sending binary data over sockets

Sukanta sukanta.hazra at gmail.com
Mon Jul 3 17:10:24 EDT 2006


thorley at gmail.com wrote:
> Greetings, since there was no reponse to my previous post about an
> existing FastCGI server in python, I've taken to writing my own. (which
> of course I'll share--*if* there's something to share ;)
>
> My problem now, is that I need to send certain binary data over a
> socket. That is, I want to make some bytes, and stuff them in a TCP
> packet, send them down the pipe, and then listen for a response.
>
> socket.send, as best I can tell, will only send strings. I've read on
> the list other conversations where the recommendation was to use xdrlib
> or struct. But it appears that is only useful when you control the
> client and the server. PLEASE correct me if I'm wrong, but using struct
> just encodes the binary data as a string, right?
>
> # Example sending binary data as a string
> s = socket.socket()
> s.connect(("127.0.0.1", 8000))
> packet = struct.pack('4B', 1, 2, 3, 4)
> s.send(packet)
>
> In my understaing the above just sends the string '\x01\x02\x03\x04',
> not raw binary data. I've looked at Billy the Kid and pcap, which are
> cool but not what I need.
>

It will send the 4 bytes, binary, and not the string as you assumed. If
you want to satisfy yourself, run tcpdump (or ethereal) to observe what
is being sent.


> Do I have to build my own packets from scratch and encode all the
> TCP/IP headers myself to get this to work?
>
> Solutions and Corrections welcome and appreciated.
> Thanks very much
> 
> --
> matthew




More information about the Python-list mailing list