package p1; import java.net.InetAddress; public class testIp { public static void main(String[] args) throws Exception { System.out.println(convertIPToLong("124.74.26.54")); System.out.println(convertLongToIP(2085231158)); } public static long convertIPToLong(String ip) throws Exception { InetAddress IPAddr = InetAddress.getByName(ip); if(IPAddr == null) return 0L; byte bytes[] = IPAddr.getAddress(); if(bytes.length < 4) { return 0L; } else { long l0 = bytes[0] & 255; long l1 = bytes[1] & 255; long l2 = bytes[2] & 255; long l3 = bytes[3] & 255; return l0 << 24 | l1 << 16 | l2 << 8 | l3; } } public static String convertLongToIP(long ipInJava) throws Exception { byte bytes[] = new byte[4]; bytes[0] = (byte)(int)((ipInJava >> 24) % 256L); bytes[1] = (byte)(int)((ipInJava >> 16) % 256L); bytes[2] = (byte)(int)((ipInJava >> 8) % 256L); bytes[3] = (byte)(int)(ipInJava % 256L); InetAddress IPAddr = InetAddress.getByAddress(bytes); return IPAddr.getHostAddress(); } }
java-ip的string和long转换
原创2009213408 博主文章分类:java ©著作权
文章标签 java ip long-string 文章分类 Java 后端开发
下一篇:经验
-
java中判断String类型为空和null的方法
java中判断String类型为空和null的方法
System 字符串 Apache