Search code examples
phpbittorrentendiannesstracker

big-endian ip address into 4 byte binary with php


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


Solution

  • 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