I am building a BitTorrent
Terminal prototype using Python where, while doing the peer handshake with the IP given by the UDP tracker, got a socket error 10060.
Given below is the code of my peer_Handshake
function:
def peer_handshake(peer_ip, peer_port, info_hash, peer_id):
peer_connect = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
encoded_peer_id = peer_id.encode('utf-8')
try:
peer_connect.connect((peer_ip, peer_port))
peer_connect.settimeout(5)
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)
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()
the output is given as follows:
I try to run the code and expecting a successful handshake.
Socket error 10060 means "connection timeout".
You are setting the timeout value after connect()
. I thing you want to setup it before.