在使用Python解析网络数据包时,使用网络字节序解析,参见下表。

C语言的数据类型和Python的数据类型对照表请参见下表。

接下来对封包与解包进行举例说明。
| version | type | id | content | 
|---|---|---|---|
| unsigned short | unsigned short | unsigned int | unsigned int | 
封包
        package = ""   # 初始化字符串变量
        vertsion = 0x0001
        type =  0x0003
        id = 0x12345678
        content = 0xab12ef45
       
        package += struct.pack('!H', vertsion) 
        package += struct.pack('!H', type)
        package += struct.pack('!I', id)  
        package += struct.pack('!I', content)  
解包
         package = receive()  # 接收网络数据包
         vertsion = 0x0001
         type =  0x0003
         id = 0x12345678
         content = 0xab12ef45
       
         vertsion =  struct.unpack('!H', package[0:2]) 
         type = struct.unpack('!H', package[2:4])
         id = struct.unpack('!I', package[4:8]) 
         content = struct.unpack('!I', package[8:12])  
来源:oschina
链接:https://my.oschina.net/u/1863491/blog/809399