DHT是什么
- DHT全称叫分布式哈希表(Distributed Hash Table),是一种分布式存储方法。在不需要服务器的情况下,每个客户端负责一个小范围的路由,并负责存储一小部分数据,从而实现整个DHT网络的寻址和存储。
- 各种博客已经有很多关于DHT介绍,这里就不详细列举了
加入DHT网络可以做什么
- 老司机开车(神秘代码)
- P2P资源共享
DHT网络的其中一种协议实现(Kademlia)
- 要加入一个DHT网络,需要首先知道这个网络中的任意一个节点。如何获得这个节点?在一些开源的P2P软件中,会提供一些节点地址
- 主要协议
- ping(用于确定某个节点是否在线。这个请求主要用于辅助路由表的更新)
- find_node(用于查找某个节点,以获得其地址信息。)
- get_peer(通过资源的infohash获得资源对应的peer列表。)
- announce_peer(通知其他节点自己开始下载某个资源,announce_peer中会携带get_peer回应消息里的token。)
DHT爬虫的工作原理
- 通过其他节点的announce_peer发来的infohash确认网络中有某个资源可被下载
- 通过从网络中获取这个资源的种子文件,来获得该资源的描述
- 不停的认识新节点,让远程节点保存自身到远程的路由表中
爬虫做的工作
- BOOTSTRAP过程,加入DHT网络(主动认识DHT网络的其中一个节点)
- 加入进DHT网络后。远端节点会主动告诉我们它认识哪些节点
- 认识远端节点认识的节点
- 当远端成功保存自身节点到远端路由表中的时候,目的达成
- 等待远端的announce_peer消息
- 成功获取远端的下载hash
- 开车!(雾
使用Python实现的爬虫:
# coding: utf-8
import socket
from hashlib import sha1 from random import randint from struct import unpack, pack from socket import inet_aton, inet_ntoa from bisect import bisect_left from threading import Timer # from time import sleep from bencode import bencode, bdecode BOOTSTRAP_NODES = [ ("router.bittorrent.com", 6881), ("dht.transmissionbt.com", 6881), ("router.utorrent.com", 6881) ] TID_LENGTH = 4 KRPC_TIMEOUT = 10 REBORN_TIME = 5 * 60 K = 8 def entropy(bytes): s = "" for i in range(bytes): s += chr(randint(0, 255)) return s # """把爬虫"伪装"成正常node, 一个正常的node有ip, port, node ID三个属性, 因为是基于UDP协议, # 所以向对方发送信息时, 即使没"明确"说明自己的ip和port时, 对方自然会知道你的ip和port, # 反之亦然. 那么我们自身node就只需要生成一个node ID就行, 协议里说到node ID用sha1算法生成, # sha1算法生成的值是长度是20 byte, 也就是20 * 8 = 160 bit, 正好如DHT协议里说的那范围: 0 至 2的160次方, # 也就是总共能生成1461501637330902918203684832716283019655932542976个独一无二的node. # ok, 由于sha1总是生成20 byte的值, 所以哪怕你写SHA1(20)或SHA1(19)或SHA1("I am a 2B")都可以, # 只要保证大大降低与别人重复几率就行. 注意, node ID非十六进制, # 也就是说非FF5C85FE1FDB933503999F9EB2EF59E4B0F51ECA这个样子, 即非hash.hexdigest(). """ def random_id(): hash = sha1() hash.update( entropy(20) ) return hash.digest() def decode_nodes(nodes): n = [] length = len(nodes) if (length % 26) != 0: return n for i in range(0, length, 26): nid = nodes[i:i+20] ip = inet_ntoa(nodes[i+20:i+24]) port = unpack("!H", nodes[i+24:i+26])[0] n.append( (nid, ip, port) ) return n def encode_nodes(nodes): strings = [] for node in nodes: s = "%s%s%s" % (node.nid, inet_aton(node.ip), pack("!H", node.port)) strings.append(s) return "".join(strings) def intify(hstr): #"""这是一个小工具, 把一个node ID转换为数字. 后面会频繁用到.""" return long(hstr.encode('hex'), 16) #先转换成16进制, 再变成数字 def timer(t, f): Timer(t, f).start() class BucketFull(Exception): pass class KRPC(object): def __init__(self): self.types = { "r": self.response_received, "q": self.query_received } self.actions = { "ping": self.ping_received, "find_node": self.find_node_received, "get_peers": self.get_peers_received, "announce_peer": self.announce_peer_received, } self.socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) self.socket.bind(("0.0.0.0", self.port)) def find_node_handler(self,msg): pass def response_received(self, msg, address): self.find_node_handler(msg) def query_received(self, msg, address): try: self.actions[msg["q"]](msg, address) except KeyError: pass def send_krpc(self, msg, address): try: self.socket.sendto(bencode(msg), address) except: pass class Client(KRPC): def __init__(self, table): self.table = table timer(KRPC_TIMEOUT, self.timeout) timer(REBORN_TIME, self.reborn) KRPC.__init__(self) def find_node(self, address, nid=None): print "find node:",address nid = self.get_neighbor(nid) if nid else self.table.nid tid = entropy(TID_LENGTH) msg = { "t": tid, "y": "q", "q": "find_node", "a": {"id": nid, "target": random_id()} } self.send_krpc(msg, address) def find_node_handler(self, msg): try: nodes = decode_nodes(msg["r"]["nodes"]) for node in nodes: (nid, ip, port) = node if len(nid) != 20: continue if nid == self.table.nid: continue self.find_node( (ip, port), nid ) except KeyError: pass def joinDHT(self): for address in BOOTSTRAP_NODES: self.find_node(address) def timeout(self): if len( self.table.buckets ) < 2: self.joinDHT() timer(KRPC_TIMEOUT, self.timeout) def reborn(self): self.table.nid = random_id() self.table.buckets = [ KBucket(0, 2**160) ] timer(REBORN_TIME, self.reborn) def start(self): self.joinDHT() while True: try: (data, address) = self.socket.recvfrom(65536) msg = bdecode(data) self.types[msg["y"]](msg, address) except Exception: pass def get_neighbor(self, target): return target[:10]+random_id()[10:] class Server(Client): def __init__(self, master, table, port): self.table = table self.master = master self.port = port Client.__init__(self, table) def ping_received(self, msg, address): try: nid = msg["a"]["id"] msg = { "t": msg["t"], "y": "r", "r": {"id": self.get_neighbor(nid)} } self.send_krpc(msg, address) self.find_node(address, nid) except KeyError: pass def find_node_received(self, msg, address): try: target = msg[