天天看點

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

}
           

繼續閱讀