【问题标题】:Peer not responding to Handshake Message in BitTorrent Protocol对等方未响应 BitTorrent 协议中的握手消息
【发布时间】:2021-01-23 09:47:18
【问题描述】:

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

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

知道我的错误是什么吗?

【问题讨论】:

    标签: python torrent


    【解决方案1】:

    您的示例代码存在一些问题。核心问题是握手中的标头错误地将“协议”大写,如果此标头不是逐字节正确的,大多数 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)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-01-30
      • 2022-08-10
      相关资源
      最近更新 更多