/**
* 字符串ip转换为long
* @param 字符串ip
* @return
*/
public static long getStringIpToLong(String ip) {
String[] ips = ip.split("[.]");
long num = 16777216L*Long.parseLong(ips[0]) + 65536L*Long.parseLong(ips[1]) + 256*Long.parseLong(ips[2]) + Long.parseLong(ips[3]);
return num;
}
/**
* 长整型ip转换为string
* @param long型ip
* @return
*/
public static String getLongIpToString(long ipLong) {
long mask[] = {0x000000FF,0x0000FF00,0x00FF0000,0xFF000000};
long num = 0;
StringBuffer ipInfo = new StringBuffer();
for(int i=0;i<4;i++){
num = (ipLong & mask[i])>>(i*8);
if(i>0) ipInfo.insert(0,".");
ipInfo.insert(0,Long.toString(num,10));
}
return ipInfo.toString();
}
/**
* @param ip
* @return 长整形数值转化为ip地址
* @author wenc
*/
public static String long2ip(long ip) {
int[] b = new int[4];
b[0] = (int) ((ip >> 24) & 0xff);
b[1] = (int) ((ip >> 16) & 0xff);
b[2] = (int) ((ip >> 8) & 0xff);
b[3] = (int) (ip & 0xff);
String x;
Integer p;
p = new Integer(0);
x = p.toString(b[0]) + "." + p.toString(b[1]) + "." + p.toString(b[2])
+ "." + p.toString(b[3]);
return x;
}
public static void main(String[] args) {
test4 t = new test4();
System.out.println("转换的long值为:"+t.getStringIpToLong("192.168.4.5"));
System.out.println("转换的ip地址为:"+t.long2ip(Long.valueOf("-101058055")));
}