is Iana Reserved Private Network IP Address by regex - Java java.util.regex

Java examples for java.util.regex:Match IP Address

Description

is Iana Reserved Private Network IP Address by regex

Demo Code


//package com.java2s;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Main {
    public static void main(String[] argv) throws Exception {
        String address = "java2s.com";
        System.out.println(isIanaReservedPrivateNetworkAddress(address));
    }/*  w  w w.  j a va 2  s. co m*/

    public static final Pattern IPV4_PATTERN = Pattern
            .compile("(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})");

    public static boolean isIanaReservedPrivateNetworkAddress(String address) {
        return isIanaReservedPrivateNetworkAddress(parseIpv4Address(address));
    }

    private static boolean isIanaReservedPrivateNetworkAddress(int[] octets) {
        return (octets[0] == 10)
                || (octets[0] == 172 && octets[1] >= 16 && octets[1] < 32)
                || (octets[0] == 192 && octets[1] == 168);
    }

    public static int[] parseIpv4Address(String address) {
        Matcher m = IPV4_PATTERN.matcher(address);
        if (!m.find()) {
            throw new RuntimeException("Invalid IP address: " + address);
        }
        int[] octets = new int[4];
        octets[0] = Integer.parseInt(m.group(1));
        octets[1] = Integer.parseInt(m.group(2));
        octets[2] = Integer.parseInt(m.group(3));
        octets[3] = Integer.parseInt(m.group(4));
        return octets;
    }
}

Related Tutorials