【发布时间】:2011-12-07 04:34:53
【问题描述】:
我正在尝试将 PHP 代码转换为 python。
所有值都以网络字节顺序(大端)发送。
协议规范中的REQUEST基本上是
响应是
对应的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 文档明确说明了哪些是 Big-Endian 格式。
遗憾的是,我无法理解在 python 中使用哪种格式。请帮我选择正确的格式。
编辑: 没有得到任何回应,所以我会说更多。
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。
【问题讨论】:
-
在linux-junky.blogspot.com/2011/10/… 中展示了如何使用协议检索数据的示例
标签: php python sockets network-programming