PHP转换ip地址

ip转换

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
/**
 * 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';
    }
}

  

posted @   橙子与柠檬  阅读(20)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
点击右上角即可分享
微信分享提示