Reading and manipulating binary data

Bob Halley halley at dnspython.org
Sat Aug 30 17:21:40 EDT 2003


"Dave" <davbucko at yahoo.com> writes:

> I am really confused as to how to use binary data with python.  I am
> currently developing a lightweight RADIUS server, which gets UDP datagrams
> from a client formatted like so:
> 
>     0                   1                   2                   3
>     0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
>    +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
>    |     Code      |  Identifier   |            Length             |
>    +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
>    |                                                               |
>    |                     Request Authenticator                     |
>    |                                                               |
>    |                                                               |
>    +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
>    |  Attributes ...
>    +-+-+-+-+-+-+-+-+-+-+-+-+-
> 
> I can read() the data easily enough from the socket.  However, when I have
> read it, it is very difficult to manipulate.  I can't convert it to an
> integer or a string which is driving me crazy...  I have seen a lot of posts
> recommending struct for dealing with binary data, but I can't get it to like
> mine.  I get all sorts of errors, like lengths don't match format etc.

struct.unpack requires the input string to be the exact length of
whatever you're trying to unpack.  You need to slice your packet
string to get the part you want to unpack.  E.g.:

        import struct

        code, identifier, length = struct.unpack('!BBH', packet[0:4])
        authenticator = packet[4 : 4 + length]

/Bob





More information about the Python-list mailing list