我想將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 –