package art.servers.types; public class IPv4 { public static long toLong(int mask) throws Exception { long result = 0xFFFFFFFFL; for(int i=0; i<(32-mask); i++) { result = result ^ ((long)1 << i); } return result; } public static long toLong(String ipAddress) throws Exception { if (ipAddress == null || ipAddress.isEmpty()) throw new Exception(); String[] octets = ipAddress.split(java.util.regex.Pattern.quote(".")); if (octets.length != 4) throw new Exception(); long ip = 0; for (int i = 3; i >= 0; i--) { long octet = Long.parseLong(octets[3 - i]); if (octet > 255 || octet < 0) throw new Exception(); ip |= octet << (i * 8); } return ip; } public static String toString (long ip) throws Exception { if (ip > 4294967295l || ip < 0) throw new Exception(); StringBuilder ipAddress = new StringBuilder(); for (int i = 3; i >= 0; i--) { int shift = i * 8; ipAddress.append((ip & (0xff << shift)) >> shift); if (i > 0) ipAddress.append("."); } return ipAddress.toString(); } }