is Loop Back IP Address by regex - Java java.util.regex

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

Description

is Loop Back 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(isLoopBackAddress(address));
    }/*  w w  w  .ja  va 2 s  .c o  m*/

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

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

    private static boolean isLoopBackAddress(int[] octets) {
        return octets[0] == 127 && octets[1] == 0 && octets[2] == 0
                && octets[3] == 1;
    }

    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