JAVA中IP和整数相互转化

摘要:
1是否将IP地址转换为字节数组?1对整数值执行AND运算符(&)0xFF,获得的数字为第四段IP。
一、基本知识点
IP ——> 整数:
?6?1把IP地址转化为字节数组
?6?1通过左移位(<<)、与(&)、或(|)这些操作转为int
整数 ——> IP:
?6?1将整数值进行右移位操作(>>>),右移24位,再进行与操作符(&)0xFF,得到的数字即为第一段IP。
?6?1将整数值进行右移位操作(>>>),右移16位,再进行与操作符(&)0xFF,得到的数字即为第二段IP。
?6?1将整数值进行右移位操作(>>>),右移8位,再进行与操作符(&)0xFF,得到的数字即为第三段IP。
?6?1将整数值进行与操作符(&)0xFF,得到的数字即为第四段IP。
二、java代码示例
IPv4Util.java
package michael.utils;
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和整数相互转化》仅用于学习参考。如对内容有疑问,请及时联系本站处理。

上篇快排代码zookeeper 介绍与集群安装下篇

宿迁高防,2C2G15M,22元/月;香港BGP,2C5G5M,25元/月 雨云优惠码:MjYwNzM=

相关文章

UVM基础之----uvm_object

uvm_void The uvm_void class is the base class for all UVM classes. uvm_object: The uvm_object class is the base class for all UVM data and hierarchical classes. uvm_object是一个uvm...

代码题(50)— 字符串的排列

1、字符串排列 输入一个字符串,按字典序打印出该字符串中字符的所有排列。例如输入字符串abc,则打印出由字符a,b,c所能排列出来的所有字符串abc,acb,bac,bca,cab和cba。 (1)交换元素位置 classSolution { public: vector<string> Permutation(stringstr)...

Android笔记之权限库AndPermission

GitHub地址:https://github.com/yanzhenjie/AndPermission 这个库可以节省不少代码量和时间 使用示例如下 findViewById(R.id.btnGetLocation).setOnClickListener(new View.OnClickListener() { @...

springboot+jwt做api的token认证

本篇和大家分享jwt(json web token)的使用,她主要用来生成接口访问的token和验证,其单独结合springboot来开发api接口token验证很是方便,由于jwt的token中存储有用户的信息并且有加密,所以适用于分布式,这样直接吧信息存储在用户本地减速了服务端存储sessiion或token的压力;如下快速使用: 1 <!--j...

深入解析synchronized

深入解析synchronized 1 常见的几个并发问题 1.可见性问题 案例演示:一个线程根据boolean类型的标记flag, while循环,另一个线程改变这个flag变量的值,另一个线程并不会停止循环。 /** * @author WGR * @create 2020/12/22 -- 20:18 */ public class Test01...

Shell字符串

1.字符串是shell编程中最常用最有用的数据类型(除了数字和字符串,也没啥其它类型好用了),字符串可以用单引号,也可以用双引号,也可以不用引号。单双引号的区别跟PHP类似。 单引号字符串的限制: 单引号里的任何字符都会原样输出,单引号字符串中的变量是无效的; 单引号字串中不能出现单引号(对单引号使用转义符后也不行)。 双引号的优点: 双引号里可以有...