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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
/**
 * Copyright (c) 2010, 新浪网支付中心
 *      All rights reserved.
 *
 * Java IP地址字符串与BigInteger的转换,
 * 支持IPv6
 *
 */
 
import java.math.BigInteger;
import java.net.InetAddress;
import java.net.UnknownHostException;
 
/**
 * IP转换大数进行比较工具
 *
 * @author yuchao1@staff.sina.com.cn
 * @since 2011-03-17
 *
 */
public final class IpLimit {
    //存放IP范围的内引类
    class IpRange{
        private String[][] ipRange;
        public IpRange(String[][] ip ){
            this.ipRange = ip;         
        }
        public String getIpAt(int row,int column){
            return ipRange[row][column];
        }
         
    }
    /**
     * 防止被实例化
     */
    private IpLimit() {
    }
 
    /**
     * 将字符串形式的ip地址转换为BigInteger
     *
     * @param ipInString
     *            字符串形式的ip地址
     * @return 整数形式的ip地址
     */
    public static BigInteger StringToBigInt(String ipInString) {
        ipInString = ipInString.replace(" ", "");
        byte[] bytes;
        if (ipInString.contains(":"))
            bytes = ipv6ToBytes(ipInString);
        else
            bytes = ipv4ToBytes(ipInString);
        return new BigInteger(bytes);
    }
 
    /**
     * 将整数形式的ip地址转换为字符串形式
     *
     * @param ipInBigInt
     *            整数形式的ip地址
     * @return 字符串形式的ip地址
     */
    public static String BigIntToString(BigInteger ipInBigInt) {
        byte[] bytes = ipInBigInt.toByteArray();
        byte[] unsignedBytes = bytes;
 
        // 去除符号位
        try {
            String ip = InetAddress.getByAddress(unsignedBytes).toString();
            return ip.substring(ip.indexOf('/') + 1).trim();
        } catch (UnknownHostException e) {
            throw new RuntimeException(e);
        }
    }
 
    /**
     * ipv6地址转有符号byte[17]
     * @param   ipv6 字符串形式的IP地址
     * @return big integer number
     */
    private static byte[] ipv6ToBytes(String ipv6) {
        byte[] ret = new byte[17];
        ret[0] = 0;
        int ib = 16;
        boolean comFlag = false;// ipv4混合模式标记
        if (ipv6.startsWith(":"))// 去掉开头的冒号
            ipv6 = ipv6.substring(1);
        String groups[] = ipv6.split(":");
        for (int ig = groups.length - 1; ig > -1; ig--) {// 反向扫描
            if (groups[ig].contains(".")) {
                // 出现ipv4混合模式
                byte[] temp = ipv4ToBytes(groups[ig]);
                ret[ib--] = temp[4];
                ret[ib--] = temp[3];
                ret[ib--] = temp[2];
                ret[ib--] = temp[1];
                comFlag = true;
            } else if ("".equals(groups[ig])) {
                // 出现零长度压缩,计算缺少的组数
                int zlg = 9 - (groups.length + (comFlag ? 1 : 0));
                while (zlg-- > 0) {// 将这些组置0
                    ret[ib--] = 0;
                    ret[ib--] = 0;
                }
            } else {
                int temp = Integer.parseInt(groups[ig], 16);
                ret[ib--] = (byte) temp;
                ret[ib--] = (byte) (temp >> 8);
            }
        }
        return ret;
    }
 
    /**
     * ipv4地址转有符号byte[5]
     * @param ipv4 字符串的IPV4地址
     * @return big integer number
     */
    private static byte[] ipv4ToBytes(String ipv4) {
        byte[] ret = new byte[5];
        ret[0] = 0;
        // 先找到IP地址字符串中.的位置
        int position1 = ipv4.indexOf(".");
        int position2 = ipv4.indexOf(".", position1 + 1);
        int position3 = ipv4.indexOf(".", position2 + 1);
        // 将每个.之间的字符串转换成整型
        ret[1] = (byte) Integer.parseInt(ipv4.substring(0, position1));
        ret[2] = (byte) Integer.parseInt(ipv4.substring(position1 + 1,
                position2));
        ret[3] = (byte) Integer.parseInt(ipv4.substring(position2 + 1,
                position3));
        ret[4] = (byte) Integer.parseInt(ipv4.substring(position3 + 1));
        return ret;
    }
    /**
     *
     * @param tip   要限制的Ip 包括Ipv6
     * @param sip   限制的开始Ip
     * @param eip   限制的结束Ip
     * @return  Boolean true通过
     *      false 受限制
     */
    public static boolean IsIp(String tip,String[][] myRange){
        boolean flag = false;
        //tbig 要测试的大数
        BigInteger tbig = IpLimit.StringToBigInt(tip);
        int rangeLength = myRange.length;
         
        for(int i=0;i<rangeLength;i++)
        {
            for(int j=0;j<myRange[i].length;j++)
            {
                //开始大数sbig和ebig
                BigInteger sbig = IpLimit.StringToBigInt(myRange[i][j]);
                j = j+1;
                BigInteger ebig = IpLimit.StringToBigInt(myRange[i][j]);
                //将大数进行比较
                //如果相等则退出循环
                if((tbig.compareTo(sbig)) == 0){
                    flag = true;
                    break;
                }
                //如果不相等则比较大小,在区间内正常
                if(((tbig.compareTo(sbig)) == 1)
                        &&((tbig.compareTo(ebig)) == -1)){
                    flag = true;
                    break;
                }
                 
            }
        }
        return flag;
    }
    /**
     * 测试程序
     * @param args
     */
    public static void main(String args[]){
         
        /*
        String ip = new String("192.168.0.1");
        BigInteger number = IpLimit.StringToBigInt(ip);
        String sip = "192.168.10.0";
        String eip = "192.168.10.255";
        System.out.println("The number ="+number);
        boolean flag = false;
        flag = IpLimit.IsIp(ip, sip, eip);
        System.out.println("The int n="+flag);
        //System.out.println("the m ="+m);
         
        //String myip = IpLimit.BigIntToString(number);
        //System.out.println("The ipv4 ="+myip);
        String ip6 = "e80:a5eb:8fc8::7ec6:8027";
        //String ip6 = "21DA:D3:AD:2F3B::9C5A";
        BigInteger num = IpLimit.StringToBigInt(ip6);
        System.out.println("The Ipv6 number ="+num);
        String myip6 = IpLimit.BigIntToString(num);
        System.out.println("The IPv6 ="+myip6);
        */
         
        //单IP限制必须写全两个
        String[][] iplimit1 ={
                {"192.168.0.1","192.168.0.255"},
                {"10.210.71.0","10.210.71.255"},
                {"202.106.182.158","202.106.182.158"}
                };
        boolean flag = false;
        String ip = "202.106.182.158";
        flag = IpLimit.IsIp(ip, iplimit1);
        System.out.println("The first test ="+flag);
         
        String ip1 = "201.101.102.21";
        flag = IpLimit.IsIp(ip1, iplimit1);
        System.out.println("The other test ="+flag);
    }
}
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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
/**
 * Copyright (c) 2010, 新浪网支付中心
 *      All rights reserved.
 *
 * Java IP地址字符串与BigInteger的转换,
 * 支持IPv6
 *
 */
 
import java.math.BigInteger;
import java.net.InetAddress;
import java.net.UnknownHostException;
 
/**
 * IP转换大数进行比较工具
 *
 * @author yuchao1@staff.sina.com.cn
 * @since 2011-03-17
 *
 */
public final class IpLimit {
    //存放IP范围的内引类
    class IpRange{
        private String[][] ipRange;
        public IpRange(String[][] ip ){
            this.ipRange = ip;         
        }
        public String getIpAt(int row,int column){
            return ipRange[row][column];
        }
         
    }
    /**
     * 防止被实例化
     */
    private IpLimit() {
    }
 
    /**
     * 将字符串形式的ip地址转换为BigInteger
     *
     * @param ipInString
     *            字符串形式的ip地址
     * @return 整数形式的ip地址
     */
    public static BigInteger StringToBigInt(String ipInString) {
        ipInString = ipInString.replace(" ", "");
        byte[] bytes;
        if (ipInString.contains(":"))
            bytes = ipv6ToBytes(ipInString);
        else
            bytes = ipv4ToBytes(ipInString);
        return new BigInteger(bytes);
    }
 
    /**
     * 将整数形式的ip地址转换为字符串形式
     *
     * @param ipInBigInt
     *            整数形式的ip地址
     * @return 字符串形式的ip地址
     */
    public static String BigIntToString(BigInteger ipInBigInt) {
        byte[] bytes = ipInBigInt.toByteArray();
        byte[] unsignedBytes = bytes;
 
        // 去除符号位
        try {
            String ip = InetAddress.getByAddress(unsignedBytes).toString();
            return ip.substring(ip.indexOf('/') + 1).trim();
        } catch (UnknownHostException e) {
            throw new RuntimeException(e);
        }
    }
 
    /**
     * ipv6地址转有符号byte[17]
     * @param   ipv6 字符串形式的IP地址
     * @return big integer number
     */
    private static byte[] ipv6ToBytes(String ipv6) {
        byte[] ret = new byte[17];
        ret[0] = 0;
        int ib = 16;
        boolean comFlag = false;// ipv4混合模式标记
        if (ipv6.startsWith(":"))// 去掉开头的冒号
            ipv6 = ipv6.substring(1);
        String groups[] = ipv6.split(":");
        for (int ig = groups.length - 1; ig > -1; ig--) {// 反向扫描
            if (groups[ig].contains(".")) {
                // 出现ipv4混合模式
                byte[] temp = ipv4ToBytes(groups[ig]);
                ret[ib--] = temp[4];
                ret[ib--] = temp[3];
                ret[ib--] = temp[2];
                ret[ib--] = temp[1];
                comFlag = true;
            } else if ("".equals(groups[ig])) {
                // 出现零长度压缩,计算缺少的组数
                int zlg = 9 - (groups.length + (comFlag ? 1 : 0));
                while (zlg-- > 0) {// 将这些组置0
                    ret[ib--] = 0;
                    ret[ib--] = 0;
                }
            } else {
                int temp = Integer.parseInt(groups[ig], 16);
                ret[ib--] = (byte) temp;
                ret[ib--] = (byte) (temp >> 8);
            }
        }
        return ret;
    }
 
    /**
     * ipv4地址转有符号byte[5]
     * @param ipv4 字符串的IPV4地址
     * @return big integer number
     */
    private static byte[] ipv4ToBytes(String ipv4) {
        byte[] ret = new byte[5];
        ret[0] = 0;
        // 先找到IP地址字符串中.的位置
        int position1 = ipv4.indexOf(".");
        int position2 = ipv4.indexOf(".", position1 + 1);
        int position3 = ipv4.indexOf(".", position2 + 1);
        // 将每个.之间的字符串转换成整型
        ret[1] = (byte) Integer.parseInt(ipv4.substring(0, position1));
        ret[2] = (byte) Integer.parseInt(ipv4.substring(position1 + 1,
                position2));
        ret[3] = (byte) Integer.parseInt(ipv4.substring(position2 + 1,
                position3));
        ret[4] = (byte) Integer.parseInt(ipv4.substring(position3 + 1));
        return ret;
    }
    /**
     *
     * @param tip   要限制的Ip 包括Ipv6
     * @param sip   限制的开始Ip
     * @param eip   限制的结束Ip
     * @return  Boolean true通过
     *      false 受限制
     */
    public static boolean IsIp(String tip,String[][] myRange){
        boolean flag = false;
        //tbig 要测试的大数
        BigInteger tbig = IpLimit.StringToBigInt(tip);
        int rangeLength = myRange.length;
         
        for(int i=0;i<rangeLength;i++)
        {
            for(int j=0;j<myRange[i].length;j++)
            {
                //开始大数sbig和ebig
                BigInteger sbig = IpLimit.StringToBigInt(myRange[i][j]);
                j = j+1;
                BigInteger ebig = IpLimit.StringToBigInt(myRange[i][j]);
                //将大数进行比较
                //如果相等则退出循环
                if((tbig.compareTo(sbig)) == 0){
                    flag = true;
                    break;
                }
                //如果不相等则比较大小,在区间内正常
                if(((tbig.compareTo(sbig)) == 1)
                        &&((tbig.compareTo(ebig)) == -1)){
                    flag = true;
                    break;
                }
                 
            }
        }
        return flag;
    }
    /**
     * 测试程序
     * @param args
     */
    public static void main(String args[]){
         
        /*
        String ip = new String("192.168.0.1");
        BigInteger number = IpLimit.StringToBigInt(ip);
        String sip = "192.168.10.0";
        String eip = "192.168.10.255";
        System.out.println("The number ="+number);
        boolean flag = false;
        flag = IpLimit.IsIp(ip, sip, eip);
        System.out.println("The int n="+flag);
        //System.out.println("the m ="+m);
         
        //String myip = IpLimit.BigIntToString(number);
        //System.out.println("The ipv4 ="+myip);
        String ip6 = "e80:a5eb:8fc8::7ec6:8027";
        //String ip6 = "21DA:D3:AD:2F3B::9C5A";
        BigInteger num = IpLimit.StringToBigInt(ip6);
        System.out.println("The Ipv6 number ="+num);
        String myip6 = IpLimit.BigIntToString(num);
        System.out.println("The IPv6 ="+myip6);
        */
         
        //单IP限制必须写全两个
        String[][] iplimit1 ={
                {"192.168.0.1","192.168.0.255"},
                {"10.210.71.0","10.210.71.255"},
                {"202.106.182.158","202.106.182.158"}
                };
        boolean flag = false;
        String ip = "202.106.182.158";
        flag = IpLimit.IsIp(ip, iplimit1);
        System.out.println("The first test ="+flag);
         
        String ip1 = "201.101.102.21";
        flag = IpLimit.IsIp(ip1, iplimit1);
        System.out.println("The other test ="+flag);
    }
}

Java IP地址字符串与BigInteger的转换, 支持IPv6的更多相关文章

  1. IP地址字符串与BigInteger的转换

    /**  * Copyright (c) 2010, 新浪网支付中心  *      All rights reserved.  *  * Java IP地址字符串与BigInteger的转换,  * ...

  2. C# IP地址与整数之间的转换

    IP地址与整数之间的转换 1.IP地址转换为整数 原理:IP地址每段可以看成是8位无符号整数即0-255,把每段拆分成一个二进制形式组合起来,然后把这个二进制数转变成一个无符号的32位整数. 举例:一 ...

  3. JAVA IP地址转成长整型方法

    JAVA IP地址转成长整型方法 代码例如以下: /** * IP转成整型 * @param ip * @return */ public static Long ip2int(String ip) ...

  4. IP地址字符串与int整数之间的无损转化

    今天鹅厂店面,最后问了一个ip地址字符串和整数间无损转化的问题,晚上有时间了手撸了一下代码. public class IPstr { public static void main(String a ...

  5. ACM_“IP地址”普及(进制转换)

    “IP地址”普及 Time Limit: 2000/1000ms (Java/Others) Problem Description: 大家都知道最近广财大校园网提速,现在就跟大家普及一下简单的互联网 ...

  6. Python—IP地址与整数之间的转换

    1. 将整数转换成IP: 思路:将整数转换成无符号32位的二进制,再8位进行分割,每8位转换成十进制即可. 方法一:#!usr/bin/python 2 #encoding=utf-8 3 #1. 将 ...

  7. Java ip地址查询,根据ip接口获得ip所在省市区,邮编,运营商等

    早上一来,项目经理就说需要添加一个用户ip归属地查询功能,然后在网上搜罗半天,研究出一个比较简单的方法,通过接口返回地址json数据 有百度接口,新浪接口,这里用的是淘宝ip接口 通过淘宝IP地址库获 ...

  8. IP地址转、整数互相转换

    知识点:一个二进制数,按位左移n位,就是把该数的值乘以2的n次方                  二进制除二即右移一位 1.IP地址转换为整数 原理:IP地址每段可以看成是8位无符号整数即0-255 ...

  9. Java获取IP地址,IpUtils工具类,Java IP地址获取

    ================================ ©Copyright 蕃薯耀 2020-01-17 https://www.cnblogs.com/fanshuyao/ import ...

随机推荐

  1. [SQL]查询某一个字段在某一段时期数据库中使用到的记录

    有些时候我们常常须要哪里用到了一些表,又或者什么时候运行了某一个存储过程.整理出了在某段时期内数据库运行的sql查询.也能够查询到数据库中某些字段的存放处.非常好非常强大.希望能帮到大家~ SELEC ...

  2. Linux网卡高级命令

    网卡的高级命令 [root@gechong ~]# mii-tool No interface specified usage: mii-tool [-VvRrwl] [-A media,... | ...

  3. http 错误码对照表

    代码 指示 2xx 成功 200 正常:请求已完成. 201 正常:紧接 POST 命令. 202 正常:已接受用于处理,但处理尚未完成. 203 正常:部分信息 — 返回的信息只是一部分. 204 ...

  4. 500 OOPS: chroot

    FTP登录时报错: 1.500 OOPS: chroot 解决方法:关闭SElinux 2.500 OOPS: vsftpd: refusing to run with writable root i ...

  5. C# 的Timer 在javascript中的实现--基于Typescript

    class Timer { //js 内置的timer对象 private _jsInnerTimerObj: any; private _enable: boolean; private _hand ...

  6. Vijos1935不可思议的清晨题解

    - 题目来源 https://vijos.org/p/1935 描写叙述 今天,是2015年2月14日,星期六,情人节. 这真是一个不可思议的日子.今天早上.我打开窗户,太阳居然从西側升了起来. 我与 ...

  7. TP3.2设置URL伪静态满足更好的SEO效果

    URL伪静态通常是为了满足更好的SEO效果,ThinkPHP支持伪静态URL设置,可以通过设置URL_HTML_SUFFIX参数随意在URL的最后增加你想要的静态后缀,而不会影响当前操作的正常执行. ...

  8. Spring +Mybatis 企业应用实战(脑图)

  9. HDUOJ-----2571跳舞毯

    跳舞毯 Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)Total Submiss ...

  10. 跨域在嵌入页面iframe中设置cookie

    在IIS  HTTP响应头 中 添加: 名称:p3p 值:CP="IDC DSP COR CURa ADMa OUR IND PHY ONL COM STA"