JAVA中IP和整数相互转化介绍

在项目中经常会用到IP(v4)范围判定比较的功能,一般将IP转化为整数再进行比较。
一、基本知识点

IP ——> 整数:

  • 把IP地址转化为字节数组
  • 通过左移位(<<)、与(&)、或(|)这些操作转为int

整数 ——> IP:

  • 将整数值进行右移位操作(>>>),右移24位,再进行与操作符(&)0xFF,得到的数字即为第一段IP。
  • 将整数值进行右移位操作(>>>),右移16位,再进行与操作符(&)0xFF,得到的数字即为第二段IP。
  • 将整数值进行右移位操作(>>>),右移8位,再进行与操作符(&)0xFF,得到的数字即为第三段IP。
  • 将整数值进行与操作符(&)0xFF,得到的数字即为第四段IP。

二、java代码示例

IPv4Util.java

Java代码 复制代码 收藏代码
  1. packagemichael.utils;
  2. importjava.net.InetAddress;
  3. /**
  4. *@authormichael<br>
  5. *blog:http://sjsky.iteye.com<br>
  6. *mail:sjsky007@gmail.com
  7. */
  8. publicclassIPv4Util{
  9. privatefinalstaticintINADDRSZ=4;
  10. /**
  11. *把IP地址转化为字节数组
  12. *@paramipAddr
  13. *@returnbyte[]
  14. */
  15. publicstaticbyte[]ipToBytesByInet(StringipAddr){
  16. try{
  17. returnInetAddress.getByName(ipAddr).getAddress();
  18. }catch(Exceptione){
  19. thrownewIllegalArgumentException(ipAddr+"isinvalidIP");
  20. }
  21. }
  22. /**
  23. *把IP地址转化为int
  24. *@paramipAddr
  25. *@returnint
  26. */
  27. publicstaticbyte[]ipToBytesByReg(StringipAddr){
  28. byte[]ret=newbyte[4];
  29. try{
  30. String[]ipArr=ipAddr.split("//.");
  31. ret[0]=(byte)(Integer.parseInt(ipArr[0])&0xFF);
  32. ret[1]=(byte)(Integer.parseInt(ipArr[1])&0xFF);
  33. ret[2]=(byte)(Integer.parseInt(ipArr[2])&0xFF);
  34. ret[3]=(byte)(Integer.parseInt(ipArr[3])&0xFF);
  35. returnret;
  36. }catch(Exceptione){
  37. thrownewIllegalArgumentException(ipAddr+"isinvalidIP");
  38. }
  39. }
  40. /**
  41. *字节数组转化为IP
  42. *@parambytes
  43. *@returnint
  44. */
  45. publicstaticStringbytesToIp(byte[]bytes){
  46. returnnewStringBuffer().append(bytes[0]&0xFF).append('.').append(
  47. bytes[1]&0xFF).append('.').append(bytes[2]&0xFF)
  48. .append('.').append(bytes[3]&0xFF).toString();
  49. }
  50. /**
  51. *根据位运算把byte[]->int
  52. *@parambytes
  53. *@returnint
  54. */
  55. publicstaticintbytesToInt(byte[]bytes){
  56. intaddr=bytes[3]&0xFF;
  57. addr|=((bytes[2]<<8)&0xFF00);
  58. addr|=((bytes[1]<<16)&0xFF0000);
  59. addr|=((bytes[0]<<24)&0xFF000000);
  60. returnaddr;
  61. }
  62. /**
  63. *把IP地址转化为int
  64. *@paramipAddr
  65. *@returnint
  66. */
  67. publicstaticintipToInt(StringipAddr){
  68. try{
  69. returnbytesToInt(ipToBytesByInet(ipAddr));
  70. }catch(Exceptione){
  71. thrownewIllegalArgumentException(ipAddr+"isinvalidIP");
  72. }
  73. }
  74. /**
  75. *ipInt->byte[]
  76. *@paramipInt
  77. *@returnbyte[]
  78. */
  79. publicstaticbyte[]intToBytes(intipInt){
  80. byte[]ipAddr=newbyte[INADDRSZ];
  81. ipAddr[0]=(byte)((ipInt>>>24)&0xFF);
  82. ipAddr[1]=(byte)((ipInt>>>16)&0xFF);
  83. ipAddr[2]=(byte)((ipInt>>>8)&0xFF);
  84. ipAddr[3]=(byte)(ipInt&0xFF);
  85. returnipAddr;
  86. }
  87. /**
  88. *把int->ip地址
  89. *@paramipInt
  90. *@returnString
  91. */
  92. publicstaticStringintToIp(intipInt){
  93. returnnewStringBuilder().append(((ipInt>>24)&0xff)).append('.')
  94. .append((ipInt>>16)&0xff).append('.').append(
  95. (ipInt>>8)&0xff).append('.').append((ipInt&0xff))
  96. .toString();
  97. }
  98. /**
  99. *把192.168.1.1/24转化为int数组范围
  100. *@paramipAndMask
  101. *@returnint[]
  102. */
  103. publicstaticint[]getIPIntScope(StringipAndMask){
  104. String[]ipArr=ipAndMask.split("/");
  105. if(ipArr.length!=2){
  106. thrownewIllegalArgumentException("invalidipAndMaskwith:"
  107. +ipAndMask);
  108. }
  109. intnetMask=Integer.valueOf(ipArr[1].trim());
  110. if(netMask<0||netMask>31){
  111. thrownewIllegalArgumentException("invalidipAndMaskwith:"
  112. +ipAndMask);
  113. }
  114. intipInt=IPv4Util.ipToInt(ipArr[0]);
  115. intnetIP=ipInt&(0xFFFFFFFF<<(32-netMask));
  116. inthostScope=(0xFFFFFFFF>>>netMask);
  117. returnnewint[]{netIP,netIP+hostScope};
  118. }
  119. /**
  120. *把192.168.1.1/24转化为IP数组范围
  121. *@paramipAndMask
  122. *@returnString[]
  123. */
  124. publicstaticString[]getIPAddrScope(StringipAndMask){
  125. int[]ipIntArr=IPv4Util.getIPIntScope(ipAndMask);
  126. returnnewString[]{IPv4Util.intToIp(ipIntArr[0]),
  127. IPv4Util.intToIp(ipIntArr[0])};
  128. }
  129. /**
  130. *根据IP子网掩码(192.168.1.1255.255.255.0)转化为IP段
  131. *@paramipAddripAddr
  132. *@parammaskmask
  133. *@returnint[]
  134. */
  135. publicstaticint[]getIPIntScope(StringipAddr,Stringmask){
  136. intipInt;
  137. intnetMaskInt=0,ipcount=0;
  138. try{
  139. ipInt=IPv4Util.ipToInt(ipAddr);
  140. if(null==mask||"".equals(mask)){
  141. returnnewint[]{ipInt,ipInt};
  142. }
  143. netMaskInt=IPv4Util.ipToInt(mask);
  144. ipcount=IPv4Util.ipToInt("255.255.255.255")-netMaskInt;
  145. intnetIP=ipInt&netMaskInt;
  146. inthostScope=netIP+ipcount;
  147. returnnewint[]{netIP,hostScope};
  148. }catch(Exceptione){
  149. thrownewIllegalArgumentException("invalidipscopeexpressip:"
  150. +ipAddr+"mask:"+mask);
  151. }
  152. }
  153. /**
  154. *根据IP子网掩码(192.168.1.1255.255.255.0)转化为IP段
  155. *@paramipAddripAddr
  156. *@parammaskmask
  157. *@returnString[]
  158. */
  159. publicstaticString[]getIPStrScope(StringipAddr,Stringmask){
  160. int[]ipIntArr=IPv4Util.getIPIntScope(ipAddr,mask);
  161. returnnewString[]{IPv4Util.intToIp(ipIntArr[0]),
  162. IPv4Util.intToIp(ipIntArr[0])};
  163. }
  164. /**
  165. *@paramargs
  166. *@throwsException
  167. */
  168. publicstaticvoidmain(String[]args)throwsException{
  169. StringipAddr="192.168.8.1";
  170. byte[]bytearr=IPv4Util.ipToBytesByInet(ipAddr);
  171. StringBufferbyteStr=newStringBuffer();
  172. for(byteb:bytearr){
  173. if(byteStr.length()==0){
  174. byteStr.append(b);
  175. }else{
  176. byteStr.append(","+b);
  177. }
  178. }
  179. System.out.println("IP:"+ipAddr+"ByInet-->byte[]:["+byteStr
  180. +"]");
  181. bytearr=IPv4Util.ipToBytesByReg(ipAddr);
  182. byteStr=newStringBuffer();
  183. for(byteb:bytearr){
  184. if(byteStr.length()==0){
  185. byteStr.append(b);
  186. }else{
  187. byteStr.append(","+b);
  188. }
  189. }
  190. System.out.println("IP:"+ipAddr+"ByReg-->byte[]:["+byteStr
  191. +"]");
  192. System.out.println("byte[]:"+byteStr+"-->IP:"
  193. +IPv4Util.bytesToIp(bytearr));
  194. intipInt=IPv4Util.ipToInt(ipAddr);
  195. System.out.println("IP:"+ipAddr+"-->int:"+ipInt);
  196. System.out.println("int:"+ipInt+"-->IP:"
  197. +IPv4Util.intToIp(ipInt));
  198. StringipAndMask="192.168.1.1/24";
  199. int[]ipscope=IPv4Util.getIPIntScope(ipAndMask);
  200. System.out.println(ipAndMask+"-->int地址段:["+ipscope[0]+","
  201. +ipscope[1]+"]");
  202. System.out.println(ipAndMask+"-->IP地址段:["
  203. +IPv4Util.intToIp(ipscope[0])+","
  204. +IPv4Util.intToIp(ipscope[1])+"]");
  205. StringipAddr1="192.168.1.1",ipMask1="255.255.255.0";
  206. int[]ipscope1=IPv4Util.getIPIntScope(ipAddr1,ipMask1);
  207. System.out.println(ipAddr1+","+ipMask1+"-->int地址段:["
  208. +ipscope1[0]+","+ipscope1[1]+"]");
  209. System.out.println(ipAddr1+","+ipMask1+"-->IP地址段:["
  210. +IPv4Util.intToIp(ipscope1[0])+","
  211. +IPv4Util.intToIp(ipscope1[1])+"]");
  212. }
  213. }
package michael.utils;

import java.net.InetAddress;

/**
 * @author michael <br>
 *         blog: http://sjsky.iteye.com <br>
 *         mail: sjsky007@gmail.com
 */
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]) + " ]");

    }
}


测试运行结果:

引用

IP: 192.168.8.1 ByInet --> byte[]: [ -64,-88,8,1 ]
IP: 192.168.8.1 ByReg --> byte[]: [ -64,-88,8,1 ]
byte[]: -64,-88,8,1 --> IP: 192.168.8.1
IP: 192.168.8.1 --> int: -1062729727
int: -1062729727 --> IP: 192.168.8.1
192.168.1.1/24 --> int地址段:[ -1062731520,-1062731265 ]
192.168.1.1/24 --> IP 地址段:[ 192.168.1.0,192.168.1.255 ]
192.168.1.1 , 255.255.255.0 --> int地址段 :[ -1062731520,-1062731265 ]
192.168.1.1 , 255.255.255.0 --> IP地址段 :[ 192.168.1.0,192.168.1.255 ]
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值