I am familiar with the theory of how 开发者_如何学运维a Distributed Hash Table (DHT) works. Is it possible to write a program that stores data to an existing DHT (such as Kademlia or Mainline DHT) ? Is there a simple 'Hello World' type of program that would show the simplest possible way to do this?
The best hello world for DHT would be to send a 'ping'
on Bittorrent's DHT to a bootstrap node. The steps are:
- Bencode a KRPC PING message.
- Send it over UDP to a bootstrap node.
- Wait for a reply.
These are the steps I just took before I began working on my own DHT implementation.
The question is might be outdated but anyway.
As was mentioned, the simplest way to say "Hello" to an existing DHT is to send a ping
message to one of DHT nodes. Let's consider Kademlia-based Mainline DHT (MDHT).
There is a bootstrap server at address router.bittorrent.com
on port 6881
. You can think about this server as a general DHT node which is permanently online. Also, you can use another node such as locally run torrent client, which uses DHT.
I've written a small example in 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)
I've used bencode
module to bencode and bdecode messages.
More information on Mainline DHT protocol can be in this document. (Note that the protocol is slightly different from original Kademlia protocol.)
精彩评论