package com.ap.Str;
/**
* 这是一个关于IP地址高效存储的问题
* 对于一个IP地址如:255.255.255.255,
* 如果在数据库中进行存储时最少需要varchar(15)来进行存储,
* 并且在这种字符串存储时如果想要做
* select ip from t_ip where ip between '192.168.11.1' and '192.168.11.150' ,
* 当末尾ip地址最后一位为三位数时,此时就查询不出数据了。
* 如何解决这一问题呢?
* 我们可以把IP地址转换为数值类型:
* 因为他们都遵循一个转换算法:A*256*256*256+B*256*256+C*256+D的算法
* 转换之后既能解决高效存储问题,也能解决IP范围比较的问题
* 这个在MySql数据库中可以通过INET_ATON、 INET_NTOA来实现
* 下面是自己实现。
* @author min
*
*/
public class IPtoLong {
/**
* 将IP地址转换为数值类型
* @param ipStr
* @return
* @throws Exception
*/
public static long ipToLong(String ipStr) throws Exception{
long result = 0;
if(ipStr != null && ipStr.length() > 0){
String[] ip = ipStr.split("\\.");
if(ip.length != 4){
throw new Exception("IP Format Error");
}
for(int i = 0; i < ip.length; i++){
int temp = Integer.parseInt(ip[i]);
result += temp * (1L<<(ip.length - i - 1) * 8);
}
}else{
throw new Exception("IP Format Error");
}
return result;
}
/**
* 将数值类型的IP地址转换回点分十进制表示的字符串类型
* @param longIP
* @return
* @throws Exception
*/
public static String longToIP(long longIP) throws Exception{
if(longIP < 0){
throw new Exception("Can not to IP...");
}
StringBuffer ipStr = new StringBuffer("");
//直接右移24位
ipStr.append(String.valueOf(longIP >>> 24));
ipStr.append(".");
//将高8位置0,然后右移16位
ipStr.append(String.valueOf((longIP & 0x00FFFFFF) >>> 16));
ipStr.append(".");
//将高16位置0,然后右移8位
ipStr.append(String.valueOf((longIP & 0x0000FFFF) >>> 8));
ipStr.append(".");
//将高24位置0
ipStr.append(String.valueOf((longIP & 0x000000FF)));
return ipStr.toString();
}
public static void main(String[] args) {
// TODO Auto-generated method stub
String ip = "192.168.123.123";
try {
long ipLong = ipToLong(ip);
System.out.println("ipLong: " + ipLong);
String ipStr = longToIP(ipLong);
System.out.println("ipStr: " + ipStr);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
IP地址存储转换
最新推荐文章于 2024-03-27 20:40:28 发布