IP地址的转换

1、Long类型的数值转换为IP地址

方法一

private String getIP(long ip_long){ String hexString=Long.toHexString(ip_long); String ip = ""+Integer.parseInt(hexString.substring(0, 2),16); for(int i=2;i<6;i=i+2){ ip = ip+"."+Integer.parseInt(hexString.substring(i, i+2), 16); } ip = ip+"."+(2+rand.nextInt(250)); return ip; }

方法二

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

2 、String到Long的转换

public long ip2long(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; }

你可能感兴趣的:(String)