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(); } }
时间: 2024-11-11 02:33:51