krisdigitx
krisdigitx

Reputation: 7126

python unpack binary data

i am writing a rlm_python module for radius which grabs location from "Accouting-Request" packet

however, the location is on binary format,

 "\001\027\002\025\001+\001\024"

when i try to unpack using struct

[root@server ~]# python 
Python 2.4.3 (#1, May  5 2011, 16:39:10) 
[GCC 4.1.2 20080704 (Red Hat 4.1.2-50)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> from struct import *
>>> unpack('hhl',"\001\027\002\025\001+\001\024" )
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
struct.error: unpack str size does not match format

any idea, how i can unpack this data?

Upvotes: 2

Views: 1948

Answers (2)

Brian Cain
Brian Cain

Reputation: 14619

Your string is eight bytes long but unpack may not expect that (the size is platform-dependent unless you use modifiers).

Python 2.4.3 (#1, May  5 2011, 16:39:10) 
[GCC 4.1.2 20080704 (Red Hat 4.1.2-50)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> from struct import *
>>> unpack('hhl',"\001\027\002\025\001+\001\024" )
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
struct.error: unpack str size does not match format
>>> unpack('=hhl',"\001\027\002\025\001+\001\024" )
(5889, 5378, 335620865)

From struct.unpack docs:

If the first character is not one of these, '@' is assumed. Native size and alignment are determined using the C compiler’s sizeof expression. This is always combined with native byte order. Standard size depends only on the format character; see the table in the Format Characters section.

Upvotes: 1

MattH
MattH

Reputation: 38245

>>> import struct
>>> data = "\001\027\002\025\001+\001\024"
>>> data
'\x01\x17\x02\x15\x01+\x01\x14'
>>> len(data)
8
>>> struct.calcsize('hhl')
16
>>> struct.calcsize('!hhl')
8
>>> struct.unpack('!hhl',data)
(279, 533, 19595540)

Depending on your architecture, the size of some elements may change unless you modify the constructor.

Upvotes: 0

Related Questions