JAVA中IP和整数相互转化 (一)

2014-11-24 11:45:06 · 作者: · 浏览: 55
一、基本知识点
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("