Skip to content

Instantly share code, notes, and snippets.

@madan712
Created September 21, 2013 16:21

Revisions

  1. madan712 created this gist Sep 21, 2013.
    36 changes: 36 additions & 0 deletions IPRangeChecker.java
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,36 @@
    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"));

    }

    }