从跟踪器解码错误消息

时间:2015-11-28 13:34:55

标签: python encoding bittorrent

我正在尝试解码来自UDP跟踪器的错误消息。 下面是我的代码。

import struct, socket
client_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
info_hash  = "%1D%D4%D1%EDQn%DB%5CL%83%90%1B%2B%F8%83%A2%19%C0%7C%98"
peer_id = "-UT1234-m%09%B2%D5%99%FA%1Fj%88%AC%0D%A7"
action =1 # announce
downloaded = 0
left = 0
uploaded = 0
event =0
ip = 0
key = 0
num_want = -1
port = 9999
announce_pack = struct.pack(">QLL20s20sQQQLLLLi",connection_id,action,transaction_id,info_hash,peer_id,down  loaded,left,uploaded,event,ip,key,num_want,port)
client_socket.sendto(announce_pack, ("tracker.ccc.de", 80))
res = client_socket.recv(1024)
try:
   action = struct.unpack(">HLLLLQQQ20s20sLLH", res[:98])
except Exception as e:
   error_action, error_tid, error_message = struct.unpack(">ii8s", res)
   raise TrackerRequestException(error_message.decode('utf-16'), "")

我可以解压缩消息但由于某种原因我收到错误消息

\uc061\u51be\u5841\ud3bf

如何将其解码为正确的文字?

我从此链接http://bittorrent.org/beps/bep_0015.html

获得了协议说明

1 个答案:

答案 0 :(得分:0)

出于多种原因可能会有例外情况;例如,您可能读取的数据太少(socket.recv(1024)可以返回更少的字节,如果那时候所有的数据都可用)。

您需要更密切地关注BEP。您需要先检查是否已收到至少8个字节,然后检查TID和操作代码。 仅当您的操作代码设置为3 时,响应才会显示错误消息。

邮件未以UTF-16编码。它应该只是ASCII数据。