Reputation: 11
I'm looking to build a bittorrrent client in python. Here is my code to find peers. It only returns none. How do I fix it?
bencodepy is a simple BEncode library
import bencodepy
import hashlib
import btdht
import binascii
from time import sleep
f = open("debian.torrent","rb")
decoded = bencodepy.decode(f.read())
info = bencodepy.encode(dict(decoded.get(b"info")))
info_hash = hashlib.sha1(info).hexdigest()
dht = btdht.DHT()
dht.start()
sleep(15) # wait for the DHT to build
while True:
print(dht.get_peers(info_hash.encode()))
sleep(1)
Upvotes: 1
Views: 614
Reputation: 25444
I'm able to get DHT peers if I use binascii.a2b_hex()
to convert the infohash into a byte string.
e.g.
import bencodepy
import hashlib
import btdht
import binascii
from time import sleep
f = open("debian.torrent","rb")
decoded = bencodepy.decode(f.read())
info = bencodepy.encode(dict(decoded.get(b"info")))
info_hash = hashlib.sha1(info).hexdigest()
print(f"{info_hash=}")
dht = btdht.DHT()
dht.start()
sleep(15) # wait for the DHT to build
while True:
print(dht.get_peers(binascii.a2b_hex(info_hash)))
sleep(1)
Testing notes: I used debian-11.3.0-amd64-netinst.iso.torrent
, available here to test this. After the 15-second bootstrapping period, it took an additional 5 seconds to find my first peer, and another second to find about 50 peers.
Upvotes: 1