Checks a IP Address string for proper IPv4 syntax via regex - Java java.util.regex

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

Description

Checks a IP Address string for proper IPv4 syntax via regex

Demo Code

/*//from  w w w . ja v a 2 s.c om
 * This file is part of VIUtils.
 *
 * Copyright ? 2012-2015 Visual Illusions Entertainment
 *
 * VIUtils is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 3 of the License,
 * or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
 * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License along with this library.
 * If not, see http://www.gnu.org/licenses/lgpl.html.
 */
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static net.visualillusionsent.utils.Verify.notNull;

public class Main{
    public static void main(String[] argv) throws Exception{
        String ip = "java2s.com";
        System.out.println(isIPv4Address(ip));
    }
    /** Internet Protocol Version 4 Syntax checking pattern */
    private static final Matcher IPv4_REGEX = Pattern.compile(
            "\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}").matcher("");
    /**
     * Checks a IP Address string for proper IPv4 syntax
     *
     * @param ip
     *         the IP Address to check
     *
     * @return {@code true} if IPv4, {@code false} otherwise
     *
     * @throws java.lang.NullPointerException
     *         if ip is null
     */
    public static boolean isIPv4Address(final String ip) {
        notNull(ip, "String ip");
        return IPv4_REGEX.reset(ip).matches();
    }
}

Related Tutorials