This code defines two functions. The first function, crc32c(), computes the CRC32C hash of a string. The second function, calculate_node_id(), calculates a valid node ID given an IP address and the number of octets to consider.

To use this code, you can call the calculate_node_id() function with an IP address (represented as an array of four or eight integers) and the number of octets to consider (4 for IPv4, 8 for IPv6). The function returns an array of 20 integers representing the node ID. You can convert this array to a string representation using the sprintf() function, as shown in the example usage code.


function crc32c($crc, $data) {
   static $table = null;

   if ($table === null) {
       $table = array();
       for ($i = 0; $i < 256; ++$i) {
           $crc = $i;
           for ($j = 0; $j < 8; ++$j) {
               $crc = ($crc & 1) ? (0x82f63b78 ^ ($crc >> 1)) : ($crc >> 1);
           }
           $table[$i] = $crc;
       }
   }

   $crc = ~$crc;
   foreach (str_split($data) as $byte) {
       $crc = $table[($crc ^ ord($byte)) & 0xff] ^ ($crc >> 8);
   }
   return ~$crc;
}

function calculate_node_id($ip, $num_octets) {
   $v4_mask = array(0x03, 0x0f, 0x3f, 0xff);
   $v6_mask = array(0x01, 0x03, 0x07, 0x0f, 0x1f, 0x3f, 0x7f, 0xff);
   $mask = ($num_octets == 4) ? $v4_mask : $v6_mask;

   for ($i = 0; $i < $num_octets; ++$i) {
       $ip[$i] &= $mask[$i];
   }

   $rand = mt_rand(0, 0xff);
   $r = $rand & 0x7;
   $ip[0] |= $r << 5;

   $crc = crc32c(0, pack('C*', ...$ip));

   $node_id = array();
   $node_id[] = ($crc >> 24) & 0xff;
   $node_id[] = ($crc >> 16) & 0xff;
   $node_id[] = (($crc >> 8) & 0xf8) | (mt_rand(0, 0x7));
   for ($i = 3; $i < 19; ++$i) {
       $node_id[] = mt_rand(0, 0xff);
   }
   $node_id[] = $rand;

   return $node_id;
}

// example usage
$ip = array(124, 31, 75, 21);
$num_octets = 4;
$node_id = calculate_node_id($ip, $num_octets);
print implode('', array_map('sprintf', array_fill(0, count($node_id), '%02x'), $node_id)) . "\n";