[Java] How to check IP in specific range

In some business case to white list requester in private IP in code level. There is no library to do so and we need to do it by own. In this example, it will use InetAddress to check the IP address is in specific range.

/**
     * Check IP address is in range.
     * @param targetIpAddress IPv4 address to be checked.
     * @param start Start IPv4 address.
     * @param end End IPv4 address.
     * @return Boolean to indicate it is in range.
     */
    public boolean isInRange(InetAddress targetIpAddress, InetAddress start, InetAddress end) {
        try {
            start = Objects.isNull(start) ? InetAddress.getByName("0.0.0.0") : start;
            end = Objects.isNull(end) ? InetAddress.getByName("255.255.255.255") : end;
        } catch (UnknownHostException exception) {
            throw new GeoLocationLookupException("Error occurred when checking IP address is in range.");
        }
        byte[] targetIpAddressByte = targetIpAddress.getAddress();
        byte[] startByte = start.getAddress();
        byte[] endByte = end.getAddress();

        boolean inRange = true;
        for (int i = 0; i < targetIpAddressByte.length; i++) {
            if ((targetIpAddressByte[i] & startByte[i]) != (startByte[i] & endByte[i])) {
                inRange = false;
                break;
            }
        }
        return inRange;
    }

In Example above, it will convert target and the range InetAddress to byte array and check with AND bit-by-bit. If target bit is same as start range bit and not same as end range bit, that means target is out of range and it will return false.

Unit tests

@ParameterizedTest
    @MethodSource("mockIsInRangeIpv4HappyCase")
    void isInRangeIpv4HappyCase(Inet4Address target, Inet4Address start, Inet4Address end, boolean expectedResult) {
        assertDoesNotThrow(()-> assertEquals(expectedResult, IpAddressChecker.INSTANCE.isInRange(target, start, end)));
    }

    static Stream<Arguments> mockIsInRangeIpv4HappyCase() throws UnknownHostException {
        return Stream.of(
                Arguments.of(
                        InetAddress.getByName("1.0.0.3"),
                        InetAddress.getByName("1.0.0.0"),
                        InetAddress.getByName("1.0.0.255"),
                        true
                ),
                Arguments.of(
                        InetAddress.getByName("10.2.0.3"),
                        InetAddress.getByName("10.0.0.0"),
                        InetAddress.getByName("10.0.0.255"),
                        true
                ),
                Arguments.of(
                        InetAddress.getByName("192.168.0.3"),
                        InetAddress.getByName("192.168.0.0"),
                        InetAddress.getByName("192.168.1.255"),
                        true
                ),
                Arguments.of(
                        InetAddress.getByName("1.0.0.3"),
                        InetAddress.getByName("1.0.0.5"),
                        InetAddress.getByName("1.0.0.255"),
                        false
                ),
                Arguments.of(
                        InetAddress.getByName("1.0.0.3"),
                        null,
                        InetAddress.getByName("1.0.0.255"),
                        true
                ),
                Arguments.of(
                        InetAddress.getByName("179.61.184.10"),
                        InetAddress.getByName("179.61.184.0"),
                        InetAddress.getByName("179.61.184.255"),
                        true
                ),
                Arguments.of(
                        InetAddress.getByName("1.0.0.3"),
                        InetAddress.getByName("1.0.0.0"),
                        null,
                        true
                )
        );
    }

Expected outcome

About C.H. Ling 260 Articles
a .net / Java developer from Hong Kong and currently located in United Kingdom. Thanks for Google because it solve many technical problems so I build this blog as return. Besides coding and trying advance technology, hiking and traveling is other favorite to me, so I will write down something what I see and what I feel during it. Happy reading!!!

Be the first to comment

Leave a Reply

Your email address will not be published.


*


This site uses Akismet to reduce spam. Learn how your comment data is processed.