Bittorrent协议TCP通信示例

时间:2015-11-01 11:56:22

标签: python sockets bittorrent

我正在尝试实施一个bittorent客户端,如果我成功连接到同行,我就会陷入困境,但我不知道如何与同伴沟通。

我设法解码了torrent数据库文件,我成功地从那里获得了所有信息,我连接到TCP的对等体,我发送了握手消息,我收到了来自同行的握手消息,但之后我不知道了不接收来自对等方的任何消息(我期待有消息)。我尝试向对等方发送unchoke消息,但我开始收到一些数据,但我不知道如何理解这些数据。

这就是我现在所拥有的:

s.connect((ip, port))
print "Connected"

message = "%s%s%s%s%s" % (chr(19), "BitTorrent protocol", 8 * chr(0),
                         handshake_params["info_hash"], 
                         handshake_params["peer_id"]

s.send(message)
handshake_data = s.recv(4096)

# unchoke
m = struct.pack(">IB", 1, 1)
s.send(m)
data = s.recv(4096)

print handshake_data
print struct.unpack("B" * len(data), data)

这是输出:

BitTorrent protocolp    p�I0a��9"x`��-UT3450-��kP+�BG   ���������
(255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 253, 231, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 127, 255, 251, 255, 255, 255, 255, 255, 255, 223, 255, 255, 255, 239, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 239, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 191, 255, 255, 255, 255, 255, 127, 255, 221, 255, 255, 255, 255, 255, 191, 191, 255, 255, 127, 255, 255, 255, 255, 191, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 191, 255, 255, 255, 255, 255, 255, 247, 255, 255, 255, 255, 255, 255, 255, 255, 255, 239, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 191, 255, 255, 255, 255, 255, 255, 255, 255, 251, 255, 255, 251, 254, 255, 255, 255, 255, 255, 255, 255, 255, 255, 252, 0, 0, 0, 5, 4, 0, 0, 4, 191, 0, 0, 0, 5, 4, 0, 0, 1, 123, 0, 0, 0, 5, 4, 0, 0, 2, 122, 0, 0, 0, 5, 4, 0, 0, 2, 126, 0, 0, 0, 5, 4, 0, 0, 2, 177, 0, 0, 0, 5, 4, 0, 0, 2, 104, 0, 0, 0, 5, 4, 0, 0, 1, 37, 0, 0, 0, 5, 4, 0, 0, 0, 174, 0, 0, 0, 5, 4, 0, 0, 4, 157, 0, 0, 0, 5, 4, 0, 0, 0, 4, 0, 0, 0, 5, 4, 0, 0, 3, 172, 0, 0, 0, 5, 4, 0, 0, 2, 241, 0, 0, 0, 5, 4, 0, 0, 1, 90, 0, 0, 0, 5, 4, 0, 0, 3, 251, 0, 0, 0, 5, 4, 0, 0, 2, 200, 0, 0, 0, 5, 4, 0, 0, 0, 179, 0, 0, 0, 5, 4, 0, 0, 0, 180, 0, 0, 0, 5, 4, 0, 0, 3, 113, 0, 0, 0, 5, 4, 0, 0, 4, 181, 0, 0, 0, 5, 4, 0, 0, 1, 16, 0, 0, 0, 5, 4, 0, 0, 2, 169, 0, 0, 0, 5, 4, 0, 0, 4, 81, 0, 0, 0, 5, 4, 0, 0, 2, 57, 0, 0, 0, 5, 4, 0, 0, 1, 219)

握手数据看起来不错。我无法弄清楚为什么我在那里得到这么多255个字节。我试图使用length_prefix,message_id,payload格式对消息进行解码,但由于我在开头得到了这么多255个字节,因此消息的长度非常大,而且我没有那么大的消息。

我应该尝试过滤掉任何噪音吗?如果你向右滚动很多,你会发现在某些时候字节开始变得不错,但我不知道如何处理消息的开头。

1 个答案:

答案 0 :(得分:0)

  

s.recv(4096)

您只是读取一些未指定长度的数据块,可能是TCP缓冲区中的任何内容。

Bittorrent是基于消息的。 TCP是一个字节流,这意味着它不能很好地将远程对等体发送的数据切换成消息,你必须自己做。