39

How to write a simple bittorrent application. Something like a "hello world" using a bittorrent library, I mean a simplest of the application to understand the working of bittorrent. I would prefer a python or a C/C++ implementation, but it can be any language. Platform is not an issues either, but i would prefer Linux.

Recommendations for the library to follow, I have downloaded the source code for one (i think official bittorrent) from - http://sourceforge.net/projects/bittorrent/develop. But, I see a lot of other libraries at http://en.wikipedia.org/wiki/Comparison_of_BitTorrent_clients#Libraries. I would appreciate recommendations on this.

How to test an application if all you have is one laptop.

Vivek Sharma
  • 3,794
  • 7
  • 38
  • 48

1 Answers1

90

You should try libtorrent (rasterbar). http://libtorrent.org

If you want to write your client in python, on linux, install it with:

sudo apt-get install python-libtorrent

A very simple example of python code to use it to download a torrent:

import libtorrent as lt
import time
import sys

ses = lt.session({'listen_interfaces': '0.0.0.0:6881'})

info = lt.torrent_info(sys.argv[1])
h = ses.add_torrent({'ti': info, 'save_path': '.'})
s = h.status()
print('starting', s.name)

while (not s.is_seeding):
    s = h.status()

    print('\r%.2f%% complete (down: %.1f kB/s up: %.1f kB/s peers: %d) %s' % (
        s.progress * 100, s.download_rate / 1000, s.upload_rate / 1000,
        s.num_peers, s.state), end=' ')

    alerts = ses.pop_alerts()
    for a in alerts:
        if a.category() & lt.alert.category_t.error_notification:
            print(a)

    sys.stdout.flush()

    time.sleep(1)

print(h.status().name, 'complete')
Arvid
  • 10,915
  • 1
  • 32
  • 40
  • 4
    Wow. They really achieved their goal of "easy to use". This is an excellent implementation! – Matt Joiner Mar 09 '12 at 14:53
  • Can you tell me what is this doing? `ses.listen_on(6881, 6891)` and why those values? –  Aug 01 '14 at 20:55
  • 6881 is the listen port. If binding to that listen port fails, libtorrent will try to increment it by one and try again. If it keeps failing until it reaches 6891, it will stop trying and just fail. errors are reported as alerts. – Arvid Aug 01 '14 at 23:17
  • What is supposed to be used for the cl argument (in `sys.argv[1]`?) I tried both a path to a `.torrent` file and a magnet link. – galois Jun 01 '16 at 19:41
  • the path to a .torrent file – Arvid Jun 01 '16 at 21:40
  • I'm trying to get the torrent info by providing the infohash but the code stuck in the while loop `while (not h.has_metadata())` https://stackoverflow.com/questions/45520804/libtorrent-get-metadata any thought please? – Muaaz Khalid Aug 06 '17 at 03:19
  • Can you please also help here on how to setup in macXos? – Pratap Alok Raj Jun 17 '21 at 14:21