Java IP地址转成长整型方法
代码如下:
/** * IP转成整型 * @param ip * @return */ public static Long ip2int(String ip){ Long num = 0L; if (ip == null){ return num; } try{ ip = ip.replaceAll("[^0-9\\.]", ""); //去除字符串前的空字符 String[] ips = ip.split("\\."); if (ips.length == 4){ num = Long.parseLong(ips[0], 10) * 256L * 256L * 256L + Long.parseLong(ips[1], 10) * 256L * 256L + Long.parseLong(ips[2], 10) * 256L + Long.parseLong(ips[3], 10); num = num >>> 0; } }catch(NullPointerException ex){ System.out.println(ip); } return num; }
Java 长整型转换为IP地址的方法
代码如下:
/** * 整型解析为IP地址 * @param num * @return */ public static String int2iP(Long num){ String str = null; Long[] tt = new Long[4]; tt[0] = (num >>> 24) >>> 0; tt[1] = ((num << 8) >>> 24) >>> 0; tt[2] = (num << 16) >>> 24; tt[3] = (num << 24) >>> 24; str = (tt[0]) + "." + (tt[1]) + "." + (tt[2]) + "." + (tt[3]); return str; }