所有哈希值

时间:2016-02-26 13:09:39

标签: python udp bittorrent torrent

我成功地设法与跟踪器连接。连接建立后,我请求抓取。 Tracker以正确的字节顺序返回响应,但(Seeder,Leecher,Completed)torrent的信息总是为零,这似乎很愚蠢。

我怀疑哈希信息编码问题,但我无法提出解决方案。我使用以下python代码块进行抓取。

import os
import bencode
import struct
import socket
import urlparse
import binascii


def loadFile(f_name):
    user_home = os.path.expanduser('~')
    path = user_home+'/completetorrent/data/'+ f_name
    return open(path,'rb')

def getSocket():
    sock = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
    sock.settimeout(8)
    return sock

def getConnection(url):
    parsed = urlparse.urlparse(url)
    hostname = socket.gethostbyname(parsed.hostname)
    port = parsed.port
    return (hostname,port)

def main():
    f = loadFile('test1.torrent')
    decoded = bencode.bdecode(f.read())

    #Connect request starts
    buff = ''
    buff += struct.pack('!q',0x41727101980)
    buff += struct.pack('!i',0)
    buff += struct.pack('!i',123456789)

    sock = getSocket()
    conn = getConnection("udp://tracker.coppersurfer.tk:6969/announce")
    sock.sendto(buff,conn)

    #Connect Response starts
    response = sock.recvfrom(4096)[0]
    assert len(response) == 16, 'response len must be bigger than 16 but %d' % len(response)
    if struct.unpack('!i',response[0:4])[0] != 0:
        raise ValueError('Bad response')
    struct.unpack('!i',response[4:8]) #ignore transaction id

    #Scrape request starts  
    con_id = struct.unpack('!q',response[8:16])[0]
    buff = ''
    buff += struct.pack('!q',con_id)
    buff += struct.pack('!i',2)
    buff += struct.pack('!i',123456)
    hash_ = decoded['info']['pieces'][0:20]
    buff += struct.pack('!20s',hash_)
    sock.sendto(buff,conn)

    #Scrape response starts
    response = sock.recvfrom(4096)[0]

    if struct.unpack('!i',response[0:4])[0] != 2:
        raise ValueError('Bad scrape response')

    struct.unpack('!i',response[4:8]) #ignore transaction id
    seedrs = struct.unpack('!i',response[8:12])
    completed = struct.unpack('!i',response[12:16])
    leechers = struct.unpack('!i',response[16:20])

    print seedrs,completed,leechers

1 个答案:

答案 0 :(得分:0)

将info_hash转换为十六进制值。