[JAVA] Library to check if it is an IPv4 format string

Overview

I have created a library that checks if the character string is in IPv4 format and converts it to Inet4Address. Also, IPv4 format character strings of uppercase letters and symbols (eg 192.168.1.1) are allowed.

Originally, it was judged by a simple method using Inet4Address.getByName (), but I created a library because there was a problem with a certain specification (listed at the end) of getByName.

Library

import java.net.Inet4Address;
import java.net.UnknownHostException;
import java.util.regex.Pattern;

/**IPv4 utility class*/
public abstract class Ipv4AddressUtil {
    /**Maximum number of octets*/
    private static final int OCTETS_LENTGH = 4;
    /**Maximum number of octet values*/
    private static final int MAX_OCTET_VALUE = 255;
    /**Minimum octet value*/
    private static final int MIN_OCTET_VALUE = 0;
    /**IPv4 pattern*/
    private static final Pattern V4_FORMAT = Pattern
            .compile("((([01]?\\d{1,2})|(2[0-4]\\d)|(25[0-5]))\\.){3}(([01]?\\d{1,2})|(2[0-4]\\d)|(25[0-5]))");

    /**
     *Determines if the specified string is in IP address v4 format.
     *It is considered as IP address v4 format in the following cases.
     *-Composed of 4 sets of numbers, with dots as delimiters.
     *-Numbers are values with 3 digits or less in the range of 0 to 255.(Zero padding allowed)。
     *
     * @param v Judgment string
     * @return IP address true for v4 format
     */
    public static boolean isIpv4Address(String v) {
        return isIpv4Address(v, true);
    }

    /**
     *Determines if the specified string is in IP address v4 format.
     *It is considered as IP address v4 format in the following cases.
     *-Composed of 4 sets of numbers, with dots as delimiters.
     *-Numbers are values with 3 digits or less in the range of 0 to 255.(Zero padding allowed)。
     *
     * @param v Judgment string
     * @param allowEm Allows full-width characters.
     * @return IP address true for v4 format
     */
    public static boolean isIpv4Address(String v, boolean allowEm) {
        if (v == null || v.isEmpty()) {
            return false;
        }

        if (allowEm) {
            String[] octets = v.toLowerCase().replaceAll(".", ".").split("\\.");
            if (octets.length != OCTETS_LENTGH) {
                return false;
            }
            for (String octet : octets) {
                try {
                    int b = Integer.parseInt(octet);

                    if (b < MIN_OCTET_VALUE || MAX_OCTET_VALUE < b)
                        return false;
                } catch (NumberFormatException e) {
                    return false;
                }
            }
            return true;
        } else {
            return V4_FORMAT.matcher(v).matches();
        }
    }

    /**
     *Parses the specified string as Inet4Address.
     * @param v String to parse
     * @param allowEm Allows full-width characters.
     * @Inet4Address represented by the argument of the return string
     * @throws IllegalArgumentException if the string is not in IP address v4 format
     */
    public static Inet4Address parseInet4Address(String v, boolean allowEm) throws IllegalArgumentException {
        if (!isIpv4Address(v, allowEm))
            throw new IllegalArgumentException("The string to be parsed is not in IP address v4 format.");


        Inet4Address returnvalue = null;
        try {
            returnvalue = (Inet4Address) Inet4Address.getByName(v.toLowerCase().replaceAll(".", "."));
        } catch (UnknownHostException e) {} //Since the IP address v4 format has been confirmed, UnknownHostException does not occur.
        return returnvalue;
    }
}

It will be based on the code of Mr. Uepan. Thank you very much.

[Java] [Sample code] Check if it is in IP address format --I will put the Java sample code http://javasampleokiba.blog.fc2.com/blog-entry-26.html

Sample code

https://paiza.io/projects/uU5C6g6Mb4RXBm1eAE4VoQ

Behavior of Inet4Address.getByName ()

InetAddress (Java Platform SE 6) https://docs.oracle.com/javase/jp/6/api/java/net/InetAddress.html#getByName(java.lang.String)

The host name is a machine name such as "java.sun.com" or a textual representation of its IP address. If a literal IP address is specified, only the validity of the address format is checked.

A specification that returns the loopback interface address (localhost / 127.0.0.1) if null or an empty string is given. (I wish I could just raise an UnknownHostException ...) Also, all IPv4 character strings must be half-width. Sample code: https://paiza.io/projects/TA90Yho1C0BhGwIqwecACQ

reference

IP address format check | Hacknote http://hacknote.jp/archives/26988/ Check if the entered characters are IP addresses-Enter from the console screen-Java | Tell me! Goo https://oshiete.goo.ne.jp/qa/5572521.html

Recommended Posts

Library to check if it is an IPv4 format string
Get the type of an array element to determine if it is an array
If the parameter is an array, how to include it in Stopara's params.permit
How to check if an instance variable is defined in a Ruby class
Program to determine if it is a leap year
Check if a string can be converted to an int without using Integer # parseInt
It doesn't work if the Map key is an array
Is it an Android app?
Is String # format (String, Object ...) really slow?
How to insert an external library
Setting an alias because it is troublesome to enter "docker-compose" every time
[Java] Check if the character string is composed only of blanks (= Blank)
Is it possible to put the library (aar) in the Android library (aar) and use it?
[Swift5] How to compare specific times to determine if it is before or after
[Java] Is it unnecessary to check "identity" in the implementation of the equals () method?