现有DHT的Hello World

5

我熟悉分布式哈希表(DHT)的工作原理。是否可以编写一个程序将数据存储到现有的DHT中(如Kademlia或Mainline DHT)?是否有一个简单的“Hello World”类型的程序,可以展示最简单的实现方式?

2个回答

5

对于DHT来说,最好的hello world是向Bittorrent的DHT发送一个'ping'到引导节点。步骤如下:

  1. Bencode一个KRPC PING消息。
  2. 通过UDP发送给引导节点
  3. 等待回复。

这些是我在开始自己的DHT实现之前所采取的步骤。


3
问题可能已经过时,但无妨。
正如所提到的,与现有DHT打招呼的最简单方法是向其中一个DHT节点发送ping消息。让我们考虑基于Kademlia的Mainline DHT(MDHT)。
在端口6881上有一个引导服务器位于地址router.bittorrent.com上。您可以将此服务器视为常驻在线的通用DHT节点。此外,您还可以使用另一个节点,例如使用DHT的本地运行的torrent客户端。
我用Python写了一个小例子:
import bencode
import random
import socket


# Generate a 160-bit (20-byte) random node ID.
my_id = ''.join([chr(random.randint(0, 255)) for _ in range(20)])

# Create ping query and bencode it.
# "'y': 'q'" is for "query".
# "'t': '0f'" is a transaction ID which will be echoed in the response.
# "'q': 'ping'" is a query type.
# "'a': {'id': my_id}" is arguments. In this case there is only one argument -
# our node ID.
ping_query = {'y': 'q',
              't': '0f',
              'q': 'ping',
              'a': {'id': my_id}}
ping_query_bencoded = bencode.bencode(ping_query)

# Send a datagram to a server and recieve a response.
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.sendto(ping_query_bencoded,
         (socket.gethostbyname('router.bittorrent.com'), 6881))
r = s.recvfrom(1024)

ping_response = bencode.bdecode(r[0])

print(ping_response)

我使用了bencode模块对消息进行了bencode和bdecode。
有关Mainline DHT协议的更多信息可以在此文档中找到。(请注意,该协议与原始的Kademlia协议略有不同。)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接