The code snippet is used to check the IpAddress given is within a specified range. It will set the inRange boolean to true if IpAddress is within that range.
/** * @param args * @throws UnknownHostException */ public static void main(String[] args){ // TODO Auto-generated method stub //Pass the IpAdress to check whether it is in the Specified Range String ipAddress = ""; //IpAddress Ranges are to be Specified here. String ipAddressRange = ""; boolean inRange = false; if (!ipAddressRange.isEmpty()){ String[] addressRanges = ipAddressRange.split(","); for (String ipAddr:addressRanges){ String[] ipAddrLowHigh = ipAddr.split("-"); try { long ipAddrLower = ipToLong(InetAddress.getByName(ipAddrLowHigh[0])); long ipAddrHigher = ipToLong(InetAddress.getByName(ipAddrLowHigh[1])); long ipAddrToTest = ipToLong(InetAddress.getByName(ipAddress)); inRange = ipAddrToTest >= ipAddrLower && ipAddrToTest <= ipAddrHigher; System.out.println("True = If Ipaddress is within the range:::::"+inRange); if (inRange){ break; } } catch (UnknownHostException ex){ System.out.println("UnknownHostException Occurred in IFAUtils.isIpAddressRange:::"+ex.getMessage()); ex.printStackTrace(); } } } } /** * Method ipToLong. converting ipAddress to Long value for given ipAddress is in available range. * @param ipAddress contains the System ipAddress. * @return long return converted long value will return. */ public static long ipToLong(InetAddress ipAddress) { byte[] octets = ipAddress.getAddress(); long result = 0; for (byte octet : octets) { result <<= 8; result |= octet & 0xff; } return result; }