Sockets

Grant Edwards grante at visi.com
Thu Apr 7 23:06:38 EDT 2005


On 2005-04-08, Dan <dan at dontspammecauseidontlikit.com> wrote:

> But it appears that the Python socket module has no method to send
> binary data, it only sends strings.

Grasshopper, things are often not what they appear.  Likewise,
they often appear to be what they are not. Strings and binary
data are one and the same.

> So there's no argument to tell it the length, it stops when it
> gets the end of string character (null).

Nope. You're thinking of C strings. Python strings aren't
terminated with a null.  A python string can contain 0x00
bytes. Think of Python strings as fixed length arrays of octets
(AKA bytes). [I'm talking about "normal" strings.  There are
also unicode strings, but thinking about them will just make
your head hurt.]

You should probably study the "struct" module.  I think that
will answer most of your questions:

   http://docs.python.org/lib/module-struct.html

Since you're doing network stuff, pay particular attention to
the sections on byte order and alignment.  

You never want to use native byte order and alignment on the
wire or on disk.  Even if you think that the two machines will
always be the same, someday they won't be.  You, of course,
won't be there at that point, and somebody will spend a week
and half tacking down the problem and swearing at you.  Been
there, done that -- at least the tracking/swearing part.
Probably the other part too.

-- 
Grant Edwards                   grante             Yow!  There's a lot of BIG
                                  at               MONEY in MISERY if you have
                               visi.com            an AGENT!!



More information about the Python-list mailing list