在使用Python解析網絡數據包時,使用網絡字節序解析,參見下表。網絡
C語言的數據類型和Python的數據類型對照表請參見下表。code
接下來對封包與解包進行舉例說明。圖片
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)
解包it
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])