Skip to content

Instantly share code, notes, and snippets.

@madan712
Created September 21, 2013 16:21
Show Gist options
  • Save madan712/6651967 to your computer and use it in GitHub Desktop.
Save madan712/6651967 to your computer and use it in GitHub Desktop.
Java program to check IP address range. This is a simple java program to check IP address range. Here we provide a IP address to check whether it lies between start and end IP address.
import java.net.InetAddress;
import java.net.UnknownHostException;
public class IPRangeChecker {
public static long ipToLong(InetAddress ip) {
byte[] octets = ip.getAddress();
long result = 0;
for (byte octet : octets) {
result <<= 8;
result |= octet & 0xff;
}
return result;
}
public static boolean isValidRange(String ipStart, String ipEnd,
String ipToCheck) {
try {
long ipLo = ipToLong(InetAddress.getByName(ipStart));
long ipHi = ipToLong(InetAddress.getByName(ipEnd));
long ipToTest = ipToLong(InetAddress.getByName(ipToCheck));
return (ipToTest >= ipLo && ipToTest <= ipHi);
} catch (UnknownHostException e) {
e.printStackTrace();
return false;
}
}
public static void main(String[] args) {
System.out.println(isValidRange("122.170.122.0", "122.170.122.255",
"122.170.122.215"));
}
}
@karnikamit
Copy link

looks clean, thanks for the idea.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment