Reading socket binary data?

Jeremy Hylton jeremy at zope.com
Thu Feb 27 21:09:23 EST 2003


> In C:
>
> struct FOO
> {
> short a;
> char b;
> long c;
> }
>
> I can read something into a data object using the sizeof(FOO)
>
> i.e. recv(socket, buffer, sizeof(FOO),....
>
> In Python, I get
>
> data = socket.recv(1024)
>
> How to I translate data to a struct FOO type or a series of objects that
> represent those fields?

The struct module does this sort of work.
http://www.python.org/doc/current/lib/module-struct.html

I find it helpful to use a class method as a factory for classes that are
designed to be serialized using struct.  The fromString() method on class
Foo will create Foo instances from a string.  It keeps the constructor
simple.

class Foo:
    def __init__(self, a, b, c):
        self.a = a
        self.b = b
        self.c = c

    _fmt = "hcl"

    def fromString(cls, s):
        return cls(*struct.unpack(cls._fmt, s))

    fromString = classmethod(fromString)

    def toString(self):
        return struct.pack(cls._fmt, self.a, self.b, self.c)

Jeremy






More information about the Python-list mailing list