IP地址存储转换

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();
		}
	}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值