How do BitTorrent magnet links work?

前端 未结 6 2039
自闭症患者
自闭症患者 2020-11-28 17:47

For the first time I used a magnet link. Curious about how it works, I looked up the specs and didn\'t find any answers. The wiki says xt means \"exact topic\"

6条回答
  •  星月不相逢
    2020-11-28 18:26

    When I started answering your question, I didn't realize you were asking how the magnet scheme works. Just thought you wanted to know how the parts relevant to the bittorrent protocol were generated.


    The hash listed in the magnet uri is the torrent's info hash encoded in base32. The info hash is the sha1 hash of the bencoded info block of the torrent.

    This python code demonstrates how it can be calculated.

    I wrote a (very naive) C# implementation to test this out since I didn't have a bencoder on hand and it matches what is expected from the client.

    static string CalculateInfoHash(string path)
    {
        // assumes info block is last entry in dictionary
        var infokey = "e4:info";
        var offset = File.ReadAllText(path).IndexOf(infokey) + infokey.Length;
        byte[] fileHash = File.ReadAllBytes(path).Skip(offset).ToArray();
        byte[] bytes;
        using (SHA1 sha1 = SHA1.Create())
            bytes = sha1.ComputeHash(fileHash, 0, fileHash.Length - 1); // need to remove last 'e' to compensate for bencoding
        return String.Join("", bytes.Select(b => b.ToString("X2")));
    }
    

    As I understand it, this hash does not include any information on how to locate the tracker, the client needs to find this out through other means (the announce url provided). This is just what distinguishes one torrent from another on the tracker.

    Everything related to the bittorrent protocol still revolves around the tracker. It is still the primary means of communication among the swarm. The magnet uri scheme was not designed specifically for use by bittorrent. It's used by any P2P protocols as an alternative form of communicating. Bittorrent clients adapted to accept magnet links as another way to identify torrents that way you don't need to download .torrent files anymore. The magnet uri still needs to specify the tracker in order to locate it so the client may participate. It can contain information about other protocols but is irrelevant to the bittorrent protocol. The bittorrent protocol ultimately will not work without the trackers.

提交回复
热议问题