package module
v1.0.0 Latest Latest

This package is not in the latest version of its module.

Go to latest
Published: Aug 27, 2020 License: LGPL-3.0 Imports: 36 Imported by: 0



Go torrent library with nice and simple interface. Can be used as standart Go library or gomobile library (iOS / Android)


Base Features (

  • Protocol obfuscation
  • DHT
  • uTP
  • PEX
  • Magnet links
  • IP Blocklists
  • Some IPv6
  • HTTP and UDP tracker clients


  • 3: Basic BitTorrent protocol
  • 5: DHT
  • 6: Fast Extension (have all/none only)
  • 7: IPv6 Tracker Extension
  • 9: ut_metadata
  • 10: Extension protocol
  • 11: PEX
  • 12: Multitracker metadata extension
  • 15: UDP Tracker Protocol
  • 20: Peer ID convention ("-GTnnnn-")
  • 23: Tracker Returns Compact Peer Lists
  • 27: Private torrents
  • 29: uTorrent transport protocol
  • 41: UDP Tracker Protocol Extensions
  • 42: DHT Security extension
  • 43: Read-only DHT Nodes

Additional features:

  • UPnP / PMP
  • Rename Torrent top folder
  • Runtime torrent states (save state between restarts)
  • Queue Engine (active/queued torrent list)
  • Full Contorl over torrent state (download metadata, download data, stop, pause, resume)


  • 14: Local Peers Discovery
  • 19: WebSeeds


# git clone $GOPATH/src/
# go get -u


# go tool cgo libtorrent.go


Use within your android gralde project:

# gomobile bind -o libtorrent.aar

Then import your libtorrent.arr into Android Studio or Eclipse.


package main

import (


func createTorrentFileExample() {
	t1 := libtorrent.CreateTorrentFile("/Users/axet/Downloads/Prattchet")
	ioutil.WriteFile("./test.torrent", t1, 0644)

func downloadMagnetWaitExample() {
	t1 := libtorrent.AddMagnet("/tmp", "magnet:?...")

func downloadMagnetStatusExample() {
	t1 := libtorrent.AddMagnet("/tmp", "magnet:?...")
	for libtorrent.TorrentStatus(t1) == libtorrent.StatusDownloading {
		time.Sleep(100 * time.Millisecond)




View Source
const (
	StatusPaused      int32 = 0
	StatusDownloading int32 = 1
	StatusSeeding     int32 = 2
	StatusChecking    int32 = 3
	StatusQueued      int32 = 4
View Source
const (
	PieceEmpty    int32 = 0 // gray
	PieceComplete int32 = 1 // blue
	PieceChecking int32 = 2 // yellow
	PiecePartial  int32 = 3 // green, when booth empty and completed
	PieceWriting  int32 = 4 // red, when have partial pieces
	PieceUnpended int32 = 5 // ltgray, empy pieces can be unpended
View Source
const WEBSEED_BUF = 64 * 1024 // read buffer size
View Source
const WEBSEED_CONCURENT = 4 // how many concurent downloading total
View Source
const WEBSEED_SPLIT = 10 * 1024 * 1024 // how large split for single sizes
View Source
const WEBSEED_TIMEOUT = time.Duration(5 * time.Second) // dial up and socket read timeouts
View Source
const WEBSEED_URL_CONCURENT = 2 // how many concurent downloading per one Url


View Source
var (
	Version                  = ""
	Bep20                    = ""
	SocketsPerTorrent int    = 40
	BindAddr          string = ":53007"
View Source
var ActiveCount = 3
View Source
var CONTENT_RANGE = regexp.MustCompile("bytes (\\d+)-(\\d+)/(\\d+)")
View Source
var QueueTimeout = (30 * time.Minute).Nanoseconds()
View Source
var (
	RefreshPort = (1 * time.Minute).Nanoseconds()


func AddMagnet

func AddMagnet(path string, magnet string) int


Add magnet link to download list

func AddTorrent

func AddTorrent(file string) int


Add torrent from local file and seed.

func AddTorrentFromBytes

func AddTorrentFromBytes(path string, buf []byte) int

func AddTorrentFromURL

func AddTorrentFromURL(path string, url string) int


Add torrent from local file or remote url.

func CheckTorrent

func CheckTorrent(i int)


Check torrent file consisteny (pices hases) on a disk. Pause torrent if downloading, resume after.

func Close

func Close()

func CloseMetaInfo

func CloseMetaInfo()

func Count

func Count() int

Get Torrent Count

func Create

func Create() bool


Create libtorrent object

func CreateMetainfo

func CreateMetainfo(root string) int

func CreateMetainfoBuilder

func CreateMetainfoBuilder(b MetainfoBuilder) int

func CreateTorrentFile

func CreateTorrentFile(root string) []byte

func CreateTorrentFileFromMetaInfo

func CreateTorrentFileFromMetaInfo() []byte

func CreateTorrentFromMetaInfo

func CreateTorrentFromMetaInfo() int

func DownloadMetadata

func DownloadMetadata(i int) bool

Download only metadata from magnet link and stop torrent

func Error

func Error() string

func GetTorrent

func GetTorrent(i int) []byte

Get Torrent file from runtime torrent

func HashMetaInfo

func HashMetaInfo(piece int) bool

func ListenAddr

func ListenAddr() string

func LoadTorrent

func LoadTorrent(path string, buf []byte) int


Load runtime torrent data from saved state file

func MetaTorrent

func MetaTorrent(i int) bool

func Pause

func Pause()

func Paused

func Paused() bool

func PendingCompleted

func PendingCompleted(i int) bool

func Port

func Port(i int) string

func PortCheck

func PortCheck() (bool, error)

func PortCount

func PortCount() int

func RemoveTorrent

func RemoveTorrent(i int)

Remote torrent for library

func Resume

func Resume()

func SaveTorrent

func SaveTorrent(i int) []byte


Every torrent application restarts it require to check files consistency. To avoid this, and save machine time we need to store torrents runtime states completed pieces and other information externaly.

Save runtime torrent data to state file

func SetDefaultAnnouncesList

func SetDefaultAnnouncesList(str string)

func SetDownloadRate

func SetDownloadRate(i int)

func SetUploadRate

func SetUploadRate(i int)

func StartTorrent

func StartTorrent(i int) bool

Separate load / create torrent from network activity.

Start announce torrent, seed/download

func StopTorrent

func StopTorrent(i int)

Stop torrent from announce, check, seed, download

func TorrentActive

func TorrentActive(i int) bool

func TorrentBytesCompleted

func TorrentBytesCompleted(i int) int64

func TorrentBytesLength

func TorrentBytesLength(i int) int64

func TorrentFileDeleteUnselected

func TorrentFileDeleteUnselected(i int)

func TorrentFileRename

func TorrentFileRename(i int, f int, n string) bool


To implement this we need to keep two Metainfo one for network operations, and second for local file storage.

func TorrentFilesCheck

func TorrentFilesCheck(i int, p int, b bool)

func TorrentFilesCheckAll

func TorrentFilesCheckAll(i int, b bool)

func TorrentFilesCheckFilter

func TorrentFilesCheckFilter(i int, filter string, b bool)

func TorrentFilesCount

func TorrentFilesCount(i int) int

func TorrentHash

func TorrentHash(i int) string

func TorrentInfoComment

func TorrentInfoComment(i int, s string)

func TorrentInfoCreator

func TorrentInfoCreator(i int, s string)

func TorrentInfoName

func TorrentInfoName(i int, s string)

func TorrentMagnet

func TorrentMagnet(i int) string

Get Magnet from runtime torrent.

func TorrentMetainfo

func TorrentMetainfo(i int) *metainfo.MetaInfo

func TorrentName

func TorrentName(i int) string

func TorrentPeersCount

func TorrentPeersCount(i int) int

func TorrentPendingBytesCompleted

func TorrentPendingBytesCompleted(i int) int64

Get total bytes downloaded by pending pieces list

func TorrentPendingBytesLength

func TorrentPendingBytesLength(i int) int64

Get total bytes for pending pieces list

func TorrentPieceLength

func TorrentPieceLength(i int) int64

func TorrentPiecesCompact

func TorrentPiecesCompact(i int, p int) int32

func TorrentPiecesCompactCount

func TorrentPiecesCompactCount(i int, size int) int

func TorrentPiecesCount

func TorrentPiecesCount(i int) int

func TorrentRename

func TorrentRename(i int, n string) bool

func TorrentSetName

func TorrentSetName(i int, n string)

func TorrentStatus

func TorrentStatus(i int) int32

func TorrentStorageSet

func TorrentStorageSet(p FileStorageTorrent)

func TorrentTrackerAdd

func TorrentTrackerAdd(i int, addr string)

func TorrentTrackerRemove

func TorrentTrackerRemove(i int, url string)

func TorrentTrackersCount

func TorrentTrackersCount(i int) int

func TorrentWebSeedsCount

func TorrentWebSeedsCount(i int) int

func WaitAll

func WaitAll() bool

func WebSeedStart

func WebSeedStart(t *torrent.Torrent)


type BodyReader

type BodyReader struct {
	// contains filtered or unexported fields

func (*BodyReader) Read

func (m *BodyReader) Read(b []byte) (int, error)

type Buffer

type Buffer struct {
	// contains filtered or unexported fields

func (*Buffer) Length

func (m *Buffer) Length() int

func (*Buffer) Write

func (m *Buffer) Write(b []byte, pos int, len int) (int, error)

type BytesInfo

type BytesInfo struct {
	Downloaded int64
	Uploaded   int64

func Stats

func Stats() *BytesInfo

type File

type File struct {
	Check          bool
	Path           string
	Length         int64
	BytesCompleted int64

func TorrentFiles

func TorrentFiles(i int, p int) *File

return torrent files array

type FileStorageTorrent

type FileStorageTorrent interface {
	ReadFileAt(hash string, path string, buf *Buffer, off int64) (n int, err error) // java unable to change []byte buf if it passed as a parameter
	WriteFileAt(hash string, path string, b []byte, off int64) (n int, err error)
	Remove(hash string, path string) error
	Rename(hash string, old string, path string) error

type InfoTorrent

type InfoTorrent struct {
	Creator       string
	CreateOn      int64
	Comment       string
	DateAdded     int64
	DateCompleted int64

func TorrentInfo

func TorrentInfo(i int) *InfoTorrent

type Int64Slice

type Int64Slice []int64

func (Int64Slice) Len

func (p Int64Slice) Len() int

func (Int64Slice) Less

func (p Int64Slice) Less(i, j int) bool

func (Int64Slice) Sort

func (p Int64Slice) Sort()

func (Int64Slice) Swap

func (p Int64Slice) Swap(i, j int)

type LPDConn

type LPDConn struct {
	// contains filtered or unexported fields

func (*LPDConn) Close

func (m *LPDConn) Close()

type LPDServer

type LPDServer struct {
	// contains filtered or unexported fields

type MetainfoBuilder

type MetainfoBuilder interface {
	Name() string
	Root() string // root directory / url for torrent register
	FilesCount() (int, error)
	FilesName(i int) string
	FilesLength(i int) int64
	ReadFileAt(path string, buf *Buffer, off int64) (n int, err error) // java unable to change buf if it passed as a parameter

type MultipartReader

type MultipartReader struct {
	// contains filtered or unexported fields

func (*MultipartReader) Read

func (m *MultipartReader) Read(b []byte) (int, error)

type Peer

type Peer struct {
	Id     [20]byte
	Name   string
	Addr   string
	Source string
	// Peer is known to support encryption.
	SupportsEncryption bool
	PiecesCompleted    int64
	// how many data we downloaded/uploaded from peer
	Downloaded int64
	Uploaded   int64

func TorrentPeers

func TorrentPeers(i int, p int) *Peer

type StatsTorrent

type StatsTorrent struct {
	Downloaded  int64 // bytes
	Uploaded    int64 // bytes
	Downloading int64 // time
	Seeding     int64 // time

func TorrentStats

func TorrentStats(i int) *StatsTorrent

type TorrentState

type TorrentState struct {
	Version int `json:"version"`

	// metainfo or these
	InfoHash *metainfo.Hash `json:"hash,omitempty"`
	Name     string         `json:"name,omitempty"`
	Trackers [][]string     `json:"trackers,omitempty"`

	MetaInfo *metainfo.MetaInfo `json:"metainfo,omitempty"`
	Pieces   []bool             `json:"pieces,omitempty"`

	Root string `json:root,omitempty`

	Checks []bool `json:"checks,omitempty"`

	// Stats bytes
	Downloaded int64 `json:"downloaded,omitempty"`
	Uploaded   int64 `json:"uploaded,omitempty"`

	// dates
	AddedDate     int64 `json:"added_date,omitempty"`
	CompletedDate int64 `json:"completed_date,omitempty"`

	// time
	DownloadingTime int64 `json:"downloading_time,omitempty"`
	SeedingTime     int64 `json:"seeding_time,omitempty"`

	// .torrent
	Comment   string `json:"comment,omitempty"`
	Creator   string `json:"creator,omitempty"`
	CreatedOn int64  `json:"created_on,omitempty"`

	UrlList metainfo.UrlList `bencode:"url-list,omitempty"`

type Tracker

type Tracker struct {
	// Tracker URI or DHT, LSD, PE
	Addr         string
	Error        string
	LastAnnounce int64
	NextAnnounce int64
	Peers        int

	// scrape info
	LastScrape int64
	Seeders    int
	Leechers   int
	Downloaded int

func TorrentTrackers

func TorrentTrackers(i int, p int) *Tracker

type WebSeedUrl

type WebSeedUrl struct {
	Url        string
	Downloaded int64  // total bytes / speed test
	Error      string // error if url were removed

func TorrentWebSeeds

func TorrentWebSeeds(i int, p int) *WebSeedUrl

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL