2016-04-20 31 views
0

我需要從TCP數據包中獲取16位整數。我如何使它起作用?我很難讓我的數據類型正確。Python中的Python新增字節2.4.3

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位。

+0

它是如何不工作?請顯示整個回溯。在顯示的代碼中沒有任何明顯的內容會產生'KeyError:4784'。 – martineau

回答

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 
+0

是的,我得到它的工作。我在嵌入式系統中使用較老的Python。該結構起作用。謝謝!!!! –