Solve the packing error on peer handshake protocol

36 Views Asked by At

I am building my own BitTorrent Client ,after getting the response from the UDP tracker I got the peer list ,After getting the list I started a peer handshake with each IP and Port one by one .I used the standard format for Handshake Protocol but still the struct.pack is throwing an error :- ERROR

the code of my peer_handshake function is given as follows:

def peer_handshake(peer_ip, peer_port, info_hash, peer_id):
    peer_connect = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    encoded_peer_id = peer_id.encode('utf-8')
    
    try:
        peer_connect.settimeout(50)
        peer_connect.connect((peer_ip, peer_port))
        
        print("CONNECTION WITH THE PEER IS SUCCESSFUL.... ")
        print("STARTING A HANDSHAKE .....")
        
        pstr = b"BitTorrent protocol"
        reserved = b'\x00' * 8
        
        # Corrected handshake format
        handshake_format = ">B19s8x20s20s"
        handshake = struct.pack(handshake_format, len(pstr), pstr , reserved, info_hash, encoded_peer_id)
        print(handshake)
        peer_connect.sendall(handshake)
        print("Handshake successful with the peer.")
        
        print("Response from the peer is :-")
        response = peer_connect.recv(68)
        print(response)
        
        print("Extracting useful information from the response :-")
        peerid_len = len(peer_id)
        extracted_peer_id = response[-peerid_len:]
        print("Extracted Peer ID :-", extracted_peer_id.decode('utf-8'))
        
        extracted_info_hash = response[28:48]
        print("Extracted Info Hash :-", extracted_info_hash)
        print("\nCHECKING IF THE INFO HASH IS VALID:-")
        
        if extracted_info_hash == info_hash:
            print("Valid")
            print("Peer is Interested")
            return "Interested"
        else:
            print("Invalid")
            return "Not Interested"
    except socket.error as e:
        print(f"Socket error connecting to {peer_ip}:{peer_port}: {e}")
    except Exception as e:
        print(f"Error connecting to {peer_ip}:{peer_port}: {e}")
    finally:
        peer_connect.close()

I expect that error must be resolved and handshake must be completed.

0

There are 0 best solutions below