当前位置: 移动技术网 > IT编程>开发语言>Java > Java判断IP地址为内网IP还是公网IP的方法

Java判断IP地址为内网IP还是公网IP的方法

2019年07月22日  | 移动技术网IT编程  | 我要评论

本文实例讲述了java判断ip地址为内网ip还是公网ip的方法。分享给大家供大家参考。具体分析如下:

tcp/ip协议中,专门保留了三个ip地址区域作为私有地址,其地址范围如下:

10.0.0.0/8:10.0.0.0~10.255.255.255
172.16.0.0/12:172.16.0.0~172.31.255.255
192.168.0.0/16:192.168.0.0~192.168.255.255

那么,直接上代码吧:

复制代码 代码如下:
public static boolean internalip(string ip) {
    byte[] addr = ipaddressutil.texttonumericformatv4(ip);
    return internalip(addr);
}

public static boolean internalip(byte[] addr) {
    final byte b0 = addr[0];
    final byte b1 = addr[1];
    //10.x.x.x/8
    final byte section_1 = 0x0a;
    //172.16.x.x/12
    final byte section_2 = (byte) 0xac;
    final byte section_3 = (byte) 0x10;
    final byte section_4 = (byte) 0x1f;
    //192.168.x.x/16
    final byte section_5 = (byte) 0xc0;
    final byte section_6 = (byte) 0xa8;
    switch (b0) {
        case section_1:
            return true;
        case section_2:
            if (b1 >= section_3 && b1 <= section_4) {
                return true;
            }
        case section_5:
            switch (b1) {
                case section_6:
                    return true;
            }
        default:
            return false;
    }
}

希望本文所述对大家的java程序设计有所帮助。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网