PHP转换ip地址

橙子与柠檬 / 2024-09-22 / 原文

ip转换

/**
 * ip转换整型
 * @param int|string|null $ip ip地址
 * @return int|string|null
 */
function my_ip2long($ip)
{
    $res = false;
    if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)) {
        $res = sprintf('%u', ip2long($ip));
    } else if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6)) {
        $ip_n     = inet_pton($ip);
        $bits     = 15;
        $ipv6long = '';
        while ($bits >= 0) {
            $bin      = sprintf('%08b', (ord($ip_n[$bits])));
            $ipv6long = $bin . $ipv6long;
            $bits--;
        }
        $res = gmp_strval(gmp_init($ipv6long, 2), 10);
    }
    if ($res) {
        return $res;
    } else {
        return 0;
    }
}

/**
 * 整型转换ipv6
 * @param null|int|string $ip ip地址
 * @return string
 */
function my_long2ip($ip)
{
    if (empty($ip)) {
        return '';
    }
    $bin = gmp_strval(gmp_init($ip, 10), 2);
    if (strlen($bin) < 128) {
        $pad = 128 - strlen($bin);
        for ($i = 1; $i <= $pad; $i++) {
            $bin = '0' . $bin;
        }
    }
    $bits = 0;
    $ipv6 = '';
    while ($bits <= 7) {
        $bin_part = substr($bin, ($bits * 16), 16);
        $ipv6     .= dechex(bindec($bin_part)) . ':';
        $bits++;
    }
    $res = inet_ntop(inet_pton(substr($ipv6, 0, -1)));
    if ($res) {
        // ipv4一定包含3个.号
        if (substr_count($res, '.') === 3) {
            $res = str_replace(':', '', $res);
        }
        return $res;
    } else {
        return '0';
    }
}