import java.net.InetAddress;
/**
 * 用于IP和整数之间的相互转换
 * @author Andy.Wang
 *
 */
public class IPv4Util {
    private final static int INADDRSZ = 4;
    /**
     * 把IP地址转化为字节数组
     * @param ipAddr
     * @return byte[]
     */
    public static byte[] ipToBytesByInet(String ipAddr) {
        try {
            return InetAddress.getByName(ipAddr).getAddress();
        } catch (Exception e) {
            throw new IllegalArgumentException(ipAddr + " is invalid IP");
        }
    }
    /**
     * 把IP地址转化为int
     * @param ipAddr
     * @return int
     */
    public static byte[] ipToBytesByReg(String ipAddr) {
        byte[] ret = new byte[4];
        try {
            String[] ipArr = ipAddr.split("\\.");
            ret[0] = (byte) (Integer.parseInt(ipArr[0]) & 0xFF);
            ret[1] = (byte) (Integer.parseInt(ipArr[1]) & 0xFF);
            ret[2] = (byte) (Integer.parseInt(ipArr[2]) & 0xFF);
            ret[3] = (byte) (Integer.parseInt(ipArr[3]) & 0xFF);
            return ret;
        } catch (Exception e) {
            throw new IllegalArgumentException(ipAddr + " is invalid IP");
        }
    }
    /**
     * 字节数组转化为IP
     * @param bytes
     * @return int
     */
    public static String bytesToIp(byte[] bytes) {
        return new StringBuffer().append(bytes[0] & 0xFF).append('.').append(
                bytes[1] & 0xFF).append('.').append(bytes[2] & 0xFF)
                .append('.').append(bytes[3] & 0xFF).toString();
    }
    /**
     * 根据位运算把 byte[] -> int
     * @param bytes
     * @return int
     */
    public static int bytesToInt(byte[] bytes) {
        int addr = bytes[3] & 0xFF;
        addr |= ((bytes[2] << 8) & 0xFF00);
        addr |= ((bytes[1] << 16) & 0xFF0000);
        addr |= ((bytes[0] << 24) & 0xFF000000);
        return addr;
    }
    /**
     * 把IP地址转化为int
     * @param ipAddr
     * @return int
     */
    public static int ipToInt(String ipAddr) {
        try {
            return bytesToInt(ipToBytesByInet(ipAddr));
        } catch (Exception e) {
            throw new IllegalArgumentException(ipAddr + " is invalid IP");
        }
    }
    /**
     * ipInt -> byte[]
     * @param ipInt
     * @return byte[]
     */
    public static byte[] intToBytes(int ipInt) {
        byte[] ipAddr = new byte[INADDRSZ];
        ipAddr[0] = (byte) ((ipInt >>> 24) & 0xFF);
        ipAddr[1] = (byte) ((ipInt >>> 16) & 0xFF);
        ipAddr[2] = (byte) ((ipInt >>> 8) & 0xFF);
        ipAddr[3] = (byte) (ipInt & 0xFF);
        return ipAddr;
    }
    /**
     * 把int->ip地址
     * @param ipInt
     * @return String
     */
    public static String intToIp(int ipInt) {
        return new StringBuilder().append(((ipInt >> 24) & 0xff)).append('.')
                .append((ipInt >> 16) & 0xff).append('.').append(
                        (ipInt >> 8) & 0xff).append('.').append((ipInt & 0xff))
                .toString();
    }
    /**
     * 把192.168.1.1/24 转化为int数组范围
     * @param ipAndMask
     * @return int[]
     */
    public static int[] getIPIntScope(String ipAndMask) {
        String[] ipArr = ipAndMask.split("/");
        if (ipArr.length != 2) {
            throw new IllegalArgumentException("invalid ipAndMask with: "
                    + ipAndMask);
        }
        int netMask = Integer.valueOf(ipArr[1].trim());
        if (netMask < 0 || netMask > 31) {
            throw new IllegalArgumentException("invalid ipAndMask with: "
                    + ipAndMask);
        }
        int ipInt = IPv4Util.ipToInt(ipArr[0]);
        int netIP = ipInt & (0xFFFFFFFF << (32 - netMask));
        int hostScope = (0xFFFFFFFF >>> netMask);
        return new int[] { netIP, netIP + hostScope };
    }
    /**
     * 把192.168.1.1/24 转化为IP数组范围
     * @param ipAndMask
     * @return String[]
     */
    public static String[] getIPAddrScope(String ipAndMask) {
        int[] ipIntArr = IPv4Util.getIPIntScope(ipAndMask);
        return new String[] { IPv4Util.intToIp(ipIntArr[0]),
                IPv4Util.intToIp(ipIntArr[0]) };
    }
    /**
     * 根据IP 子网掩码(192.168.1.1 255.255.255.0)转化为IP段
     * @param ipAddr ipAddr
     * @param mask mask
     * @return int[]
     */
    public static int[] getIPIntScope(String ipAddr, String mask) {
        int ipInt;
        int netMaskInt = 0, ipcount = 0;
        try {
            ipInt = IPv4Util.ipToInt(ipAddr);
            if (null == mask || "".equals(mask)) {
                return new int[] { ipInt, ipInt };
            }
            netMaskInt = IPv4Util.ipToInt(mask);
            ipcount = IPv4Util.ipToInt("255.255.255.255") - netMaskInt;
            int netIP = ipInt & netMaskInt;
            int hostScope = netIP + ipcount;
            return new int[] { netIP, hostScope };
        } catch (Exception e) {
            throw new IllegalArgumentException("invalid ip scope express  ip:"
                    + ipAddr + "  mask:" + mask);
        }
    }
    /**
     * 根据IP 子网掩码(192.168.1.1 255.255.255.0)转化为IP段
     * @param ipAddr ipAddr
     * @param mask mask
     * @return String[]
     */
    public static String[] getIPStrScope(String ipAddr, String mask) {
        int[] ipIntArr = IPv4Util.getIPIntScope(ipAddr, mask);
        return new String[] { IPv4Util.intToIp(ipIntArr[0]),
                IPv4Util.intToIp(ipIntArr[0]) };
    }
    /**
     * @param args
     * @throws Exception
     */
    public static void main(String[] args) throws Exception {
        String ipAddr = "192.168.8.1";
        byte[] bytearr = IPv4Util.ipToBytesByInet(ipAddr);
        StringBuffer byteStr = new StringBuffer();
        for (byte b : bytearr) {
            if (byteStr.length() == 0) {
                byteStr.append(b);
            } else {
                byteStr.append("," + b);
            }
        }
        System.out.println("IP: " + ipAddr + " ByInet --> byte[]: [ " + byteStr
                + " ]");
        bytearr = IPv4Util.ipToBytesByReg(ipAddr);
        byteStr = new StringBuffer();
        for (byte b : bytearr) {
            if (byteStr.length() == 0) {
                byteStr.append(b);
            } else {
                byteStr.append("," + b);
            }
        }
        System.out.println("IP: " + ipAddr + " ByReg  --> byte[]: [ " + byteStr
                + " ]");
        System.out.println("byte[]: " + byteStr + " --> IP: "
                + IPv4Util.bytesToIp(bytearr));
        int ipInt = IPv4Util.ipToInt(ipAddr);
        System.out.println("IP: " + ipAddr + "  --> int: " + ipInt);
        System.out.println("int: " + ipInt + " --> IP: "
                + IPv4Util.intToIp(ipInt));
        String ipAndMask = "192.168.1.1/24";
        int[] ipscope = IPv4Util.getIPIntScope(ipAndMask);
        System.out.println(ipAndMask + " --> int地址段:[ " + ipscope[0] + ","
                + ipscope[1] + " ]");
        System.out.println(ipAndMask + " --> IP 地址段:[ "
                + IPv4Util.intToIp(ipscope[0]) + ","
                + IPv4Util.intToIp(ipscope[1]) + " ]");
        String ipAddr1 = "192.168.1.1", ipMask1 = "255.255.255.0";
        int[] ipscope1 = IPv4Util.getIPIntScope(ipAddr1, ipMask1);
        System.out.println(ipAddr1 + " , " + ipMask1 + "  --> int地址段 :[ "
                + ipscope1[0] + "," + ipscope1[1] + " ]");
        System.out.println(ipAddr1 + " , " + ipMask1 + "  --> IP地址段 :[ "
                + IPv4Util.intToIp(ipscope1[0]) + ","
                + IPv4Util.intToIp(ipscope1[1]) + " ]");
    }
}

JAVA中IP和整数相互转化(含有掩码的计算)的更多相关文章

  1. [转] 有关java中两个整数的交换问题

    转载申明:本文主要是用于自己学习使用,为了完善自己的只是框架,没有任何的商业目的. 原文来源:有关Java中两个整数的交换问题 如果侵权,麻烦告之,立刻删除. 在程序开发的过程,要交换两个变量的内容, ...

  2. Java中最小的整数为什么是-2147483648

    Java中最小的整数为什么是-2147483648 假如只有两位来表示数字,第一位是符号位: 00:0 01:1 11:-1,这个是负数,而且是补码,取反为00,加1成为01,就是-1 10:-2,这 ...

  3. Java中浮点型数据Float和Double进行精确计算的问题

    Java中浮点型数据Float和Double进行精确计算的问题 来源  https://www.cnblogs.com/banxian/p/3781130.html 一.浮点计算中发生精度丢失     ...

  4. 【Java编程】Java中的大整数计算

    在上一篇文章中,我们实现了c语言中的大整数的运算,并且用Miller-Rabin算法实现了对大素数的测试.本来我准备用Java代码实现大整数的运算,查了一下资料发现Java中java.math的Big ...

  5. 按公式产生随机数、java中的重载、递归、有关计算机计算的问题

    1.按公式产生随机数x1=(16807*x)%(Integer.MAX_VALUE)x=x1;通过这个公式进行随机数的产生,当产生的数字大于2e+32-2时,在用产生随机数的方式进行数字的输出.主要思 ...

  6. Java中的高精度整数和高精度小数

    在实际编码中,会遇到很多高精度的事例,比如,在计算金钱的时候就需要保留高精度小数,这样计算才不会有太大误差: 在下面的代码中,我们验证了,当两个float型的数字相加,得到的结果和我们的预期结果是有误 ...

  7. mysql中ip和整数的转换

    INET_ATON(expr) 给出一个作为字符串的网络地址的点地址表示,返回一个代表该地址数值的整数.地址可以是4或8比特地址. mysql> SELECT INET_ATON('209.20 ...

  8. Java中,当表单含有文件上传时,提交数据的如何读取

    http://blog.csdn.net/lian_zhihui1984/article/details/6822201

  9. 018、Java中除法的是用,解决除法计算精度问题

    01.代码如下: package TIANPAN; /** * 此处为文档注释 * * @author 田攀 微信382477247 */ public class TestDemo { public ...

随机推荐

  1. 【转】Win8 下 管理无线网络

    Ref:http://windows.microsoft.com/zh-CN/windows-8/manage-wireless-network-profiles 管理无线网络配置文件 适用于 Win ...

  2. JQuery点击table获取点击行的数据

    $(function () {var TaskType = '';$("#data_table tr:gt(0)").click(function () { TaskType = ...

  3. IntelliJ IDEA 激活

    方法1 进入ide主页面,help-register-license server,然后输入 http://idea.iteblog.com/key.php   或者   http://idea.la ...

  4. memcached连接说明

    memcached 客户端与服务器端通信使用的基于文本的协议,不是二进制,可通过Telnet进行互交

  5. unity模型法线反转问题

    fbx模型导入unity正常 但只要绑了骨骼,在3dmax中正常,进入unity就法线反转 原因是3dmax中模型用到复制和镜像的导出需要多一步处理 1重置变换 2反转法线 按顺序进行这两个,在绑定模 ...

  6. iOS app支付宝接口调用的一点总结(补充支付宝SDK&Demo下载地址)

    由于app内需要用到支付功能,选择了当前最流行的支付宝进行支付.在进行内嵌支付宝功能开发时,被它狠狠的耍了一把. 根据支付宝开发文档,参考demo代码.将相关支付功能加到了自己的代码中.一些根据文档来 ...

  7. jar工具的使用

  8. beanutils包下载

  9. B. Mancala (Codeforces Round #478 (Div. 2))

    #include <bits/stdc++.h> using namespace std; ; typedef long long ll; ll a[maxn]; ll b[maxn]; ...

  10. python 基础(十) 面向对象

    面向对象 一.概念 类(class): 用来描述具有相同属性和方法的对象的集合 对象是类的实例化 类变量:类变量在整个实例化的对象中是共用的.定义在类中 并且是函数体外的 实例变量:只能作用于 当前类 ...