Python 2.4.3中Python Bytes的新功能

时间:2016-04-20 23:15:16

标签: python tcp

我需要从TCP数据包中获取16位整数。我如何让它工作?我很难弄清楚我的数据类型。

HOST = 'localhost'
PORT = 502
#s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
s.bind((HOST,PORT))
s.listen(1)
conn, addr = s.accept()
data = []
data = conn.recv(1024)
print 'Connect by', addr
while (data):
    sys.stdout.write(hexdump(data))
    sys.stdout.write(struct.unpack("h", data[2:4])) # here is error!!!!
    data = conn.recv(1024)

I get this error when running:
Connect by ('127.0.0.1', 52741)
0000  00 27 00 00 00 06 01 03 00 00 00 0a               .'..........
KeyError: 4784
Press any key to continue . . .

如何改进我的变量类型,以便从TCP数据包中提取16位和32位整数。

1 个答案:

答案 0 :(得分:0)

data[2:2]  # this is your issue (it is an empty string always) ... not sure what you want here
print repr("Hello"[2:2]) # this is no bytes of string
print repr("hello"[2:4]) # this is 2 bytes of string

# you need 2 bytes to unpack a short
print struct.unpack("h","")  # error!!
print struct.unpack("h","b") # error!!
print struct.unpack("h","bq") # ok awesome!

# you also cannot have too many bytes
print struct.unpack("h","bbq") # error!!!!!!!

#but you can use unpack_from to just take the bytes you define
print struct.unpack_from("h","bbq") # ok awesome again!

您可以打印出所有字节的短值,如下所示

while data:
    sys.stdout.write(struct.unpack_from("h", data)) # print this short
    data = data[2:] # advance the buffer to the next short