Change IPv4 to IPv6 string

后端 未结 3 1309
被撕碎了的回忆
被撕碎了的回忆 2021-01-12 17:33

Sander Steffann mentioned in a previous question of mine:

Addresses like 0000:0000:0000:0000:0000:0000:192.168.0.1 are written as 0000:0000:0000:00

3条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-12 18:01

    I can't believe I wrote this all out in one go and it worked the first time.

    $strIP = '0000:0000:0000:0000:0000:0000:192.168.0.1';
    $arrIP = explode(':', $strIP);
    
    if( preg_match('/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/', $arrIP[count($arrIP)-1]) ) {
      $ip4parts = explode('.', $arrIP[count($arrIP)-1]);
      $ip6trans = sprintf("%02x%02x:%02x%02x", $ip4parts[0], $ip4parts[1], $ip4parts[2], $ip4parts[3]);
      $arrIP[count($arrIP)-1] = $ip6trans;
    
      $strIP = implode(':', $arrIP);
    }
    echo $strIP; //output: 0000:0000:0000:0000:0000:0000:c0a8:0001
    

    Basically:

    1. Explode the string on :
    2. Check if the last quad is formatted like an IP4 address
    3. Explode the last quad on .
    4. Re-print the IP4 octets into two hex quads
    5. Replace the IP4 quad with the new ones
    6. Implode the array on :.

提交回复
热议问题