場景
部分PHP系統存儲在資料庫中的IP位址為ip2long的結果,Java系統需要與之互動,是以我們需要一個支援IP位址轉換的工具類。
分析
1.IPv4位址可轉換為一個32位整型的數字,
2.單純移位操作會出現高位符号為負的情況需要轉換
測試驗證
Java
PHP
JavaScript
示例代碼
package org.ybygjy.util;
/**
* IPv4位址與整型類型互轉
* @author WangYanCheng
* @version 2015年8月16日
*/
public class IPConvert {
public static long ip2Long(String ipAddr) {
String[] tmpIPData = ipAddr.split("\\.");
int result = ((toUnsignedInt(Integer.parseInt(tmpIPData[0]))<< 24)
| (toUnsignedInt(Integer.parseInt(tmpIPData[1])) << 16)
| (toUnsignedInt(Integer.parseInt(tmpIPData[2])) << 8)
| (toUnsignedInt(Integer.parseInt(tmpIPData[3]))));
//無符号轉換
long rtnValue = toUnsignedLong(result);
return rtnValue;
}
/**
* Int無符号轉換
* @param intVal
* @return intVal
*/
private static int toUnsignedInt(int intVal) {
int result = intVal & 0x7fff;
if (intVal < 0) {
result = result | 0x8000;
}
return result;
}
/**
* Long無符号轉換
* @param longVal
* @return longVal
*/
private static long toUnsignedLong(long longVal) {
//注意十六進制表示的變量類型為Long(L)
long result = longVal & 0x07fffffffL;
if (longVal < 0) {
result = result | 0x080000000L;
}
return result;
}
/**
* 給定數值轉換為對應的IP位址
* @param longValue
* @return
*/
public static String long2IP(long longValue) {
int ip1 = (int) (longValue >> 24) & 0xff;
int ip2 = (int) (longValue >> 16) & 0xff;
int ip3 = (int) (longValue >> 8) & 0xff;
int ip4 = (int) longValue & 0xff;
return ip1 + "." + ip2 + "." + ip3 + "." + ip4;
}
/**
* 測試入口
* @param args
* @throws UnknownHostException
*/
public static void main(String[] args) {
String[] ipArr = {"182.118.0.0", "10.1.7.106", "222.223.254.254"};
for(int i = 0; i < ipArr.length; i++) {
String ipAddr = ipArr[i];
Long ipNumber = IPConvert.ip2Long(ipAddr);
String ipStr = IPConvert.long2IP(ipNumber);
System.out.println(ipNumber + "=>" + ipStr);
}
}
}
下載下傳示例代碼
http://download.csdn.net/detail/ybygjy/9013135