sending binary data over sockets

Grant Edwards grante at visi.com
Mon Jul 3 17:13:03 EDT 2006


On 2006-07-03, thorley at gmail.com <thorley at gmail.com> wrote:

> 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?

Right.  Strings are binary data.

> # 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.

The string '\x01\x02\x03\x04' consists of four octets having
the values 0x01, 0x02, 0x03, 0x04.

Are those not the four octets you wanted to send?

-- 
Grant Edwards                   grante             Yow!  I want EARS! I
                                  at               want two ROUND BLACK
                               visi.com            EARS to make me feel warm
                                                   'n secure!!



More information about the Python-list mailing list