对等方未响应BitTorrent协议中的握手消息

2024-06-17 12:12:13 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在和同伴握手。这就是握手的样子:

b'\x13BitTorrent Protocol\x00\x00\x00\x00\x00\x00\x00\x00\x08O\xae=J2\xc5g\x98Y\xafK\x9e\x8d\xbb\x7f`qcG\x08O\xff=J2\xc5g\x98Y\xafK\x9e\x8d\xbb\x7f`qcG'

但是,我得到一个空的b''作为响应。我已将超时设置为10。 这是我的密码:

            clientsocket=socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            clientsocket.settimeout(5)
            print("trying")
            try:
                clientsocket.connect((ip,port))
            except:
                continue
            print('connected')
            #print(req)
            clientsocket.send(req)
            clientsocket.settimeout(10)
            try:
                buffer = clientsocket.recv(1048)
            except:
                continue

知道我的错误是什么吗


Tags: socketprintx00x7fj2settimeoutxbbclientsocket
1条回答
网友
1楼 · 发布于 2024-06-17 12:12:13

您的示例代码存在一些问题。核心问题是握手中的头错误地将“协议”大写,如果此头不是逐字节正确的,大多数BitTorrent实现将丢弃TCP连接

下面是一个稍微整理过的代码版本:

# IP and Port, obviously change these to match where the server is
ip, port = "127.0.0.1", 6881

import socket

# Broken up the BitTorrent header to multiple lines just to make it easier to read

# The main header, note the lower "p" in protocol, that's important
req = b'\x13'
req += b'BitTorrent protocol'

# The optional bits, note that normally some of these are set by most clients
req += b'\x00\x00\x00\x00\x00\x00\x00\x00'
# The Infohash we're interested in.  Let python convert the human readable
# version to a byte array just to make it easier to read
req += bytearray.fromhex("5fff0e1c8ac414860310bcc1cb76ac28e960efbe")
# Our client ID.  Just a random blob of bytes, note that most clients
# use the first bytes of this to mark which client they are
req += bytearray.fromhex("5b76c604def8aa17e0b0304cf9ac9caab516c692")

# Open the socket
clientsocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
clientsocket.settimeout(5)
print("Trying")
clientsocket.connect((ip,port))
print('Connected')
# Note: Use sendall, in case the handshake doesn't make it one packet for
# whatever reason
clientsocket.sendall(req)
# And see what the server sends back. Note that really you should keep reading
# till one of two things happens:
#  - Nothing is returned, likely meaning the server "hung up" on us, probably
#    because it doesn't care about the infohash we're talking about
#  - We get 68 bytes in the handshake response, so we have a full handshake
buffer = clientsocket.recv(1048)
print(buffer)

相关问题 更多 >