user886596
user886596

Reputation: 2440

BitTorrent Peer Handshake

I'm trying to send a BitTorrent handshake to a peer but it's not working. Can someone figure out what I'm doing wrong? len is supposed to come back with something, but it's currently nil.

require 'bencode'
require 'digest/sha1'

file = File.open('./python.torrent').read
info_hash = Digest::SHA1.hexdigest(a['info'].bencode)

# Here's what parsed_response['peers'] returns:
# [{"ip"=>"8.19.35.234", "peer id"=>"-lt0C20-\x90\xE0\xE6\x0E\xD0\x8A\xE5\xA2\xF2b(!",          
# "port"=>9898}]
peer_id = parsed_response['peers'].first['peer id']

send_string = "\023BitTorrent protocol\0\0\0\0\0\0\0\0" << info_hash << peer_id

# ip and port are my current internet ip and 6881 respectively
client = TCPSocket.new ip, port

# What I'm sending over
client.send("\023BitTorrent protocol\0\0\0\0\0\0\0\0" << info_hash << peer_id, 0)
len = client.recv(1)
puts len

Here's what send_string looks like in the end: enter image description here

Upvotes: 1

Views: 2552

Answers (2)

Utsav Chokshi
Utsav Chokshi

Reputation: 1395

While having handshake from your side, PeerID used should be yours , not of the other side.

So your message should look like this :

peer_id = "-MY0001-123456654321"
client.send("\023BitTorrent protocol\0\0\0\0\0\0\0\0" << info_hash << peer_id, 0)

If you are developing your own bit-torrent client then you can have your own format for peer id following standards mentioned by bit-torrent protocol. You can read more about peer id here: https://wiki.theory.org/BitTorrentSpecification#peer_id

If you have any confusion in future , start any bittorrent client and follow wire-shark packets. You will understand, where you are making mistake.

I am attaching a sample handshake message here : enter image description here

Here "-KS0001-123456654321" is peerid for my bittorrent client.

Upvotes: 1

labulaka
labulaka

Reputation: 48

I cant write ruby. This is python code:

send_string = chr(19)+"BitTorrent Protocol"+8*chr(0)+info_hash+peer_id

Upvotes: 0

Related Questions