How to make a handshake with a peer in the BitTorrent network?

Here is my code:

import socket
import time

sock = socket.socket()
sock.connect((peer_id, peer_port))

message = b'\x13BitTorrent protocol\x00\x00\x00\x00\x00\x00\x00\x00' + bytes('1A6948C96FA8302C74DA680C7360D1486A52B2F9'.lower(), encoding="UTF8") + b'66788486352714431784'

sock.send(message)

print('s')

while True:
try:
 resp = sock.recv(len(message))
print(resp)
 if resp != b":
break
except:
 pass


The response from the PIR I get an empty string b". And this line is constantly printed in the console
What's the problem?
March 23rd 20 at 18:45
1 answer
March 23rd 20 at 18:47
Solution
In line 7 info_hash have to encode to bytes like so:
hashlib.sha1(torrent_file['info']).digest()

And in my code I used the hexdigest method. The final code looks like this:
import hashlib
import bencode
import random
import socket

sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect((peer_ip, peer_host))

torrent_file = bencode.decode(open('test.torrent', 'rb').read())
info_hash_raw = hashlib.sha1(bencode.bencode(torrent_file['info'])).digest()


message = b'\x13BitTorrent protocol\x00\x00\x00\x00\x00\x10\x00\x05' + info_hash_raw + bytes(str(random.randint(10**20, 10**21-1)), encoding="UTF-8")

sock.send(message)

while True:
try:
 resp = sock.recv(len(message))
print(resp)
break
except:
 pass

Find more questions by tags BitTorrentPython