2

我正在为 radius 编写一个 rlm_python 模块,它从“Accouting-Request”数据包中获取位置

但是,该位置是二进制格式,

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

当我尝试使用 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

任何想法,我如何解压这些数据?

4

2 回答 2

1

您的字符串长度为 8 个字节,但unpack可能不会如此(大小取决于平台,除非您使用修饰符)。

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)

来自struct.unpack文档

如果第一个字符不是其中之一,则假定为“@”。本机大小和对齐方式是使用 C 编译器的 sizeof 表达式确定的。这总是与本机字节顺序相结合。标准大小仅取决于格式字符;请参阅格式字符部分中的表格。

于 2013-04-05T14:30:28.010 回答
0
>>> 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)

根据您的架构,除非您修改构造函数,否则某些元素的大小可能会发生变化。

于 2013-04-05T14:30:08.790 回答