Domanda

I am looking to create a private torrent tracker but I have came across a problem. I found in the protocol specifications that the compact response that the most clients use now is presented as binary 4 byte represendint the IP address in big-endian and 2 represent the port. I have attempted to do this but unsure of what format I should input the IP

I have attempted the following

$IP = "12.34.56.78";
$port = "12345";

$binary = pack("Nn", $IP, $port);

but when I attempt to convert this back using unpack("Nn" $binary) I just get a return of the first part of the IP addrss in this example it would be "12" I attempt to try this with a torrent client I get "internal server error"

I have also tried ip2long and when I reverse that I get the long ip but when I am unsure if this is the correct format or what, all I know it is looking for ip and port in 6 bites.

any sugestions for where I am going wrong would be greatly appreciated

Vip32

È stato utile?

Soluzione

Try this:

Packing:

$ip = "12.34.56.78";
$port = 12345;

$packed = pack("Nn", ip2long($ip), $port);

Unpacking:

$unpacked = unpack("Nip/nport", $packed);

echo "IP was ".long2ip($unpacked["ip"])."\n";
echo "Port was ".$unpacked["port"]."\n";

Output:

IP was 12.34.56.78
Port was 12345

Altri suggerimenti

To convert to binary, you will first need to convert it from the human-readable dotted decimal notation to something computer readable - pack() does not understand the dots . in your string. You can split the address into it's component parts and treat them as unsigned chars (c):

<?php

  $IP = "12.34.56.78";
  $port = "12345";

  $octets = explode('.', $IP);

  $binary = pack('ccccn', $octets[0], $octets[1], $octets[2], $octets[3], $port);

To convert back, it gets slightly more complicated. You need to use a repeater and name the components when you call unpack():

<?php

  $unpacked = unpack('c4octet/nport', $binary);

  $IP = $unpacked['octet1'].".".$unpacked['octet2'].".".$unpacked['octet3'].".".$unpacked['octet4'];
  $port = $unpacked['port'];
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top