Search code examples
python-requestsbittorrenthashlibtrackerlibtorrent

How to send requests to bittorrent tracker using python requests


I was studying the bittorrent protocol, and wanted to try out some tracker requests to get info about peers and stuff, but I am unable to receive any proper response from any of the tracker I've tried

These are what my params look like

{'info_hash': '7bf74c4fd609bf288523f7cd51af3bdbc19df610', 'peer_id': '139a3f2ff0143c9f24c19c4f95ed1378aaf449d2', 'port': '6881', 'uploaded': '0', 'downloaded': '0', 'left': '931135488', 'compact': '1', 'no_peer_id': '0', 'event': 'started'}
import bencoding
import hashlib
import secrets
import requests
import urllib

file = open('../altlinux.torrent', 'rb')
data = bencoding.bdecode(file.read())
info_hash = hashlib.sha1(bencoding.bencode(data[b'info'])).hexdigest()
params = {
    'info_hash': info_hash,
    'peer_id': secrets.token_hex(20),
    'port': '6881',
    'uploaded': '0',
    'downloaded': '0',
    'left': str(data[b'info'][b'length']),
    'compact': '1',
    'no_peer_id': '0',
    'event': 'started'
}
print(params)
page = requests.get(data[b'announce'], params=params)
print(page.text

So this is what I wrote, and I'm getting the same error,

d14:failure reason50:Torrent is not authorized for use on this tracker.e

I've even tried encoding info_hash to

urllib.parse.quote_plus(info_hash)

just to make it url encoded format insted of hexdigest

I'm not sure where I'm going wrong Can someone help with this?


Solution

  • You need to pass the raw info_hash, not an encoded version of it. The same is true of the peer_id as well:

    params = {
        'info_hash': bytes.fromhex(info_hash),
        'peer_id': bytes.fromhex(secrets.token_hex(20)),
        'port': '6881',
        'uploaded': '0',
        'downloaded': '0',
        'left': str(data[b'info'][b'length']),
        'compact': '1',
        'no_peer_id': '0',
        'event': 'started'
    }
    

    Also, it should be pointed out that this will only work for single file torrents. The way you're getting the length will need to handle the files element in torrents when you see one with multiple files, since those don't have a length entry.