最近在一個項目中被IP轉換給折騰死了,有些用LONG存儲,還有些用int, 還有些用String存儲。
看着真火大啊,轉換來轉換去的,看的頭都暈了。爲了偷懶還是自己寫幾行代碼,弄個工具轉換一下
算了,磨刀不誤砍柴功嘛。下面是轉換的代碼:
public class IPConvertor{
// IP Long to String
public String iPLong2Str(long ipAddr) {
StringBuffer sb = new StringBuffer("");
sb.append(String.valueOf((ipAddr >>> 24)));
sb.append(".");
sb.append(String.valueOf((ipAddr & 0x00FFFFFF) >>> 16));
sb.append(".");
sb.append(String.valueOf((ipAddr & 0x0000FFFF) >>> 8));
sb.append(".");
sb.append(String.valueOf((ipAddr & 0x000000FF)));
return sb.toString();
}
//String IP to Long
public long iPStr2Long(String strIPAddr) {
long[] ip = new long[4];
int pos1 = strIPAddr.indexOf(".");
int pos2 = strIPAddr.indexOf(".", pos1 + 1);
int pos3 = strIPAddr.indexOf(".", pos2 + 1);
ip[0] = Long.parseLong(strIPAddr.substring(0, pos1));
ip[1] = Long.parseLong(strIPAddr.substring(pos1+1, pos2));
ip[2] = Long.parseLong(strIPAddr.substring(pos2+1, pos3));
ip[3] = Long.parseLong(strIPAddr.substring(pos3+1));
return (ip[0] << 24) + (ip[1] << 16) + (ip[2] << 8) + ip[3];
}
//IP INT to String
public String iPInt2Str(int ipAddr) {
StringBuffer sb = new StringBuffer("");
sb.append(String.valueOf((ipAddr >>> 24)));
sb.append(".");
sb.append(String.valueOf((ipAddr & 0x00FFFFFF) >>> 16));
sb.append(".");
sb.append(String.valueOf((ipAddr & 0x0000FFFF) >>> 8));
sb.append(".");
sb.append(String.valueOf((ipAddr & 0x000000FF)));
return sb.toString();
}
//String IP to INT
public int iPStr2Int(String strIPAddr) {
int[] ip = new int[4];
int pos1 = strIPAddr.indexOf(".");
int pos2 = strIPAddr.indexOf(".", pos1 + 1);
int pos3 = strIPAddr.indexOf(".", pos2 + 1);
ip[0] = Integer.parseInt(strIPAddr.substring(0, pos1));
ip[1] = Integer.parseInt(strIPAddr.substring(pos1+1, pos2));
ip[2] = Integer.parseInt(strIPAddr.substring(pos2+1, pos3));
ip[3] = Integer.parseInt(strIPAddr.substring(pos3+1));
return (ip[0] << 24) + (ip[1] << 16) + (ip[2] << 8) + ip[3];
}
public static void main(String[] args) {
IPConvertor ipConvertor = new IPConvertor();
int ipInt = ipConvertor.iPStr2Int("115.173.195.36");
String strIPInt = ipConvertor.iPInt2Str(-100527956);
long ipLong = ipConvertor.iPStr2Long("115.173.195.36");
String strIPLong = ipConvertor.iPLong2Str(-100527956);
System.out.println(ipInt);
System.out.println(strIPInt);
System.out.println(ipLong);
System.out.println(strIPLong);
}
}