0

Say I have an array like this arr = [24, 21, 25, 40, 236, 89] which is meant to represent an IP address (first four bytes) and a port number (last 2 bytes), as in http://wiki.theory.org/BitTorrentSpecification#Tracker_Response, the binary peer section.

My question is this: how do I get the IP address and the port number from this?

arr[0..3].reverse.join '.' for the IP and arr[5] << 8 | arr[4] for the port doesn't seem to be correct.

I'm assuming here that since I do string_from_tracker.unpack 'C*' to get arr, the bits are already in the native endianness...

I'm not super sure how this is even supposed to work.

Thanks.

HRÓÐÓLFR
  • 5,842
  • 5
  • 32
  • 35

1 Answers1

1

What's the "not correct part"? I.e. what's the expected result?

At least here you have a bug. Combining the two last numbers should be done like so:

(arr[5] << 8) + arr[4]

Which gives 23020. Seems more like a Bittorrent port number.

Edit: Heh :) Actually this is equivalent to the above:

(arr[5] << 8) | arr[4]
Casper
  • 33,403
  • 4
  • 84
  • 79
  • That actually does the same thing (the bitshift creates zeroes, adding to them and or'ing is the same). The expected result is something that I can ping successfully... so really I'm assuming I'm wrong because none of the IP's I get with that method seem right. – HRÓÐÓLFR Jul 20 '11 at 17:13
  • << has higher precedence than | see http://www.techotopia.com/index.php/Ruby_Operator_Precedence#Operator_Precedence_Table – HRÓÐÓLFR Jul 20 '11 at 17:15
  • Yeah..right. Hmm. Can't help with the IP though :-/ Would be easier if we knew what it SHOULD be, and then work from there. – Casper Jul 20 '11 at 17:21
  • Btw. why do you assume you should be able to ping? Not all computers respond to ping, but perhaps you took this into account.. – Casper Jul 20 '11 at 17:25
  • Well the trouble is that I am testing my code with a random archlinux .torrent file and I'm given a list of peers. Sure, some computers block ping, but surely not all! I suppose I could get a bittorrent client and find the IP out, but it would be difficult to know if it's the same IP as the one I'm trying to decode. Does the unpack 'C*' part guarantee that it returns the bytes in native endianness? – HRÓÐÓLFR Jul 20 '11 at 17:29
  • Nevermind... I think I was doing something stupid because now that I've tried again, it seems to be working =) Thanks though. – HRÓÐÓLFR Jul 20 '11 at 17:31