我想将PHP代码转换为python。在Python中使用结构模块在pack()中选择格式
所有的值都以网络字节顺序(大端)发送。
基本上,在协议规范的请求是
和响应是
通讯PHP代码(corresponding DOC)为:
$transaction_id = mt_rand(0,65535);
$current_connid = "\x00\x00\x04\x17\x27\x10\x19\x80";
$fp = fsockopen($tracker, $port, $errno, $errstr);
$packet = $current_connid . pack("N", 0) . pack("N", $transaction_id);
fwrite($fp,$packet);
我试图找到在python相应的代码(for doc):
transaction_id = random.randrange(1,65535)
packet = "\x00\x00\x04\x17\x27\x10\x19\x80"
packet = packet + struct.pack("i", 0) + struct.pack("i", transaction_id)
clisocket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
clisocket.sendto(packet, ("tracker.istole.it", 80))
在响应中,我应该得到我在我没有收到请求发送相同TRANSACTION_ID。所以,我的猜测是,我没有使用正确的格式打包。
此外,python文档并不像PHP那样清晰。该协议指定使用Big Endian格式& PHP doc明确指出哪些是Big-Endian的。
不幸的是,我无法理解在python中使用哪种格式。请帮助我选择corrent格式。
编辑: 没有得到任何答复,所以我会说更多。
import struct
import socket
import random
clisocket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
packet = "\x00\x00\x04\x17\x27\x10\x19\x80"
transaction_id = random.randrange(1,65535)
print transaction_id
packet = packet+struct.pack(">i", 0)
packet = packet+struct.pack(">i", transaction_id)
clisocket.sendto(packet, ("tracker.istole.it", 80))
res = clisocket.recv(16)
print struct.unpack(">i", res[12:16])
根据协议规范,我应该返回相同的INTEGER。
用于该协议的完整文档是在http://bittorrent.org/beps/bep_0015.html#udp-tracker-protocol –
示出了如何使用来检索数据的示例该协议位于http://linux-junky.blogspot.com/2011/10/get-seeds-peers-completed-info-from.html –