IP地址字符串与BigInteger的转换

/**

 * Copyright (c) 2010, 新浪网支付中心

 *      All rights reserved.

 *

 * Java IP地址字符串与BigInteger的转换,

 * 支持IPv6

 *

 */

import java.math.BigInteger;

import java.net.InetAddress;

import java.net.UnknownHostException;

/**

 * IP转换大数进行比较工具

 *

 * @author [email protected]

 * @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);

    }

}

本文转自:http://www.oschina.net/code/snippet_1434_3596

时间: 2024-10-09 10:44:28

IP地址字符串与BigInteger的转换的相关文章

SQL Server使用PARSENAME函数来处理IP地址字符串

IP V4地址是用3个点分隔的字符串,有时候需要在数据库中进行处理,比如判断IP地址是否有效等. 通常想到的方法是自己写个函数,比如利用CHARINDEX.SUBSTRING等函数组合来获取IP地址的各个部分,然后处理. SQL Server用来表示对象的时候通常采取 架构名.对象名.数据库名.架构名.对象名.链接服务器名.数据库名.架构名.对象名 等方式 比如dbo.tablename.master.dbo.tablename.[192.168.1.100].master.dbo.tablen

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

1. 将整数转换成IP: 思路:将IP地址转换成无符号32位的二进制,再8位进行分割,每8位转换成十进制即可. #!usr/bin/python 2 #encoding=utf-8 3 #1. 将整数转换成32位无符号二进制 4 def intToIp(num): 5 s = [] 6 g = [] 7 h = [] 8 for i in range(32): 9 a = num%2 10 s.insert(0,a) 11 num = num/2 12 print s 13 #2. 每8位进行分

CIPAddress中获取的IP地址与CString的互相转换

// IPAddressCtrl中的IP地址转为CString CIPAddressCtrl* pIp = (CIPAddressCtrl*)GetDlgItem(IPADDRESS); BYTE bytIp1, bytIp2, bytIp3, bytIp4; pIp->GetAddress(bytIp1, bytIp2, bytIp3, bytIp4); CString strIp; strIp.Format(_T("%u.%u.%u.%u"), bytIp1, bytIp2,

将IP地址字符串形式拆成四个整数形式

/* * File: main.c * Author: liutingting */ #include<stdio.h> #include<stdlib.h> #include<Winsock2.h> #include<string.h> #include<time.h> #include <Ws2tcpip.h> #pragma comment(lib,"WS2_32.lib") int main(int arg

IP地址中的进制转换

10进制转换为2进制例子=189189>128=1  189-128=6161<64=0     61-32=2929>16=1    29-16=1313>8=1   13-8=55>4=1    5-4=11<2=0      1=1=1即转为 1011101   132132>128=1   132-128=44<64=0     4<32=04<16=04<8=04=4=1  即 100001  2进制转化为10进制例子 11101

四、IP地址转换

IP地址与端口 TCP/IP(传输控制协议/网际协议)不是一个协议,而是一组协议的总称,包括IP.TCP.UDP.ICMP.ARP等.它规范了网络上的所有通信设备,尤其是一个主机与另一个主机之间的数据交换格式以及传送方式. IP地址:是给每个连接在因特网上的主机(或路由器)分配一个在全世界范围内惟一的标识符. 一个IP地址主要由两部分组成:网络地址和主机地址. 网络地址由因特网权力机构分配,主机地址由各个网络的管理员统一分配. IP地址编制方案有两种:IPV4和IPV6 IPV4:二进制表示共3

整数与IP地址间的转换

描述 原理:ip地址的每段可以看成是一个0-255的整数,把每段拆分成一个二进制形式组合起来,然后把这个二进制数转变成一个长整数.举例:一个ip地址为10.0.3.193每段数字             相对应的二进制数10                   000010100                    000000003                    00000011193                  11000001组合起来即为:00001010 00000000

Java网络编程从入门到精通(8):用getAddress方法获得IP地址

getAddress方法和getHostAddress类似,它们的唯一区别是getHostAddress方法返回的是字符串形式的IP地址,而getAddress方法返回的是byte数组形式的IP地址.getAddress方法的定义如下: public byte[] getAddress() 这个方法返回的byte数组是有符号的.在Java中byte类型的取值范围是-128?127.如果返回的IP地址的某个字节是大于127的整数,在byte数组中就是负数.由于Java中没有无符号byte类型,因此

c++ ip地址的操作 c版

http://blog.csdn.net/cpp_funs/article/details/6988154 1.htonl ()和ntohl( ) u_long PASCAL FAR ntohl (u_long netlong); u_short PASCAL FAR ntohs (u_short netshort); ntohl( )-----网络顺序转换成主机顺序 u_long PASCAL FAR htonl (u_long hostlong); u_short PASCAL FAR ht