Quick way of expanding IPv6 Addresses with PHP

后端 未结 2 510
长发绾君心
长发绾君心 2020-12-09 22:34

I was working on a project where I needed to expand IPv6 addresses. There are not many functions out there created by other users, and the ones that exist are ugly. Some of

2条回答
  •  再見小時候
    2020-12-09 23:15

    With the help from Mike Mackintosh and Yann Milin I came up with this function:

    function expandIPv6($ip) {
        $hex = bin2hex(inet_pton($ip));
        return implode(':', str_split($hex, 4));
    }
    

    Below a more universal function witch will also extract IPv4 from an IPv4-mapped IPv6 addresses:

    function expandIPv6($ip) {
        if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4))
            return $ip;
        elseif (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6)) {
            $hex = bin2hex(inet_pton($ip));
            if (substr($hex, 0, 24) == '00000000000000000000ffff') // IPv4-mapped IPv6 addresses
                return long2ip(hexdec(substr($hex, -8)));
            return implode(':', str_split($hex, 4));
        }
        else
            return false;
    }
    

提交回复
热议问题