Java InetAddress Check isIpAddressInRange(InetAddress ipStart, InetAddress ipEnd, InetAddress ipToCheck)

Here you can find the source of isIpAddressInRange(InetAddress ipStart, InetAddress ipEnd, InetAddress ipToCheck)

Description

is Ip Address In Range

License

Open Source License

Declaration

public static boolean isIpAddressInRange(InetAddress ipStart, InetAddress ipEnd, InetAddress ipToCheck) 

Method Source Code


//package com.java2s;
//License from project: Open Source License 

import java.net.*;

public class Main {
    public static boolean isIpAddressInRange(InetAddress ipStart, InetAddress ipEnd, InetAddress ipToCheck) {
        long ipLo = inetAddressToLong(ipStart);
        long ipHi = inetAddressToLong(ipEnd);
        long ipToTest = inetAddressToLong(ipToCheck);
        return (ipToTest >= ipLo && ipToTest <= ipHi);
    }//w w  w  . j  a  v a 2 s . c  o  m

    public static boolean isIpAddressInRange(String ipStart, String ipEnd, String ipToCheck) {
        try {
            InetAddress ipLo = InetAddress.getByName(ipStart);
            InetAddress ipHi = InetAddress.getByName(ipEnd);
            InetAddress ipToTest = InetAddress.getByName(ipToCheck);
            return isIpAddressInRange(ipLo, ipHi, ipToTest);
        } catch (UnknownHostException e) {
            return false;
        }
    }

    public static long inetAddressToLong(InetAddress ip) {
        byte[] octets = ip.getAddress();
        long result = 0;
        for (byte octet : octets) {
            result <<= 8;
            result |= octet & 0xff;
        }
        return result;
    }
}

Related

  1. isCommonSubnet(InetAddress address1, InetAddress address2)
  2. isGlobalAddressV6(InetAddress addr)
  3. isHostLocalHost(InetAddress host)
  4. isInet6Compatible(InetAddress address, Inet6Address inet6Address)
  5. isInRage(InetAddress check, InetAddress bcast, int netmask)
  6. isIPLocal(final InetAddress adr)
  7. isIPv6(final InetAddress ip)
  8. isIPv6(InetAddress addr)
  9. isIPv6UniqueSiteLocal(InetAddress address)