Java IP Address Validate isIPv4AddressValid(String cidr)

Here you can find the source of isIPv4AddressValid(String cidr)

Description

Checks if the passed IP v4 address in string form is valid The address may specify a mask at the end as "/MM"

License

Open Source License

Parameter

Parameter Description
cidr the v4 address as A.B.C.D/MM

Declaration

public static boolean isIPv4AddressValid(String cidr) 

Method Source Code

//package com.java2s;
/*//from  www. j a va  2  s . com
 * Copyright (c) 2013-2014 Cisco Systems, Inc. and others.  All rights reserved.
 *
 * This program and the accompanying materials are made available under the
 * terms of the Eclipse Public License v1.0 which accompanies this distribution,
 * and is available at http://www.eclipse.org/legal/epl-v10.html
 */

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

public class Main {
    /**
     * Checks if the passed IP v4 address in string form is valid The address
     * may specify a mask at the end as "/MM"
     *
     * @param cidr the v4 address as A.B.C.D/MM
     * @return
     */
    public static boolean isIPv4AddressValid(String cidr) {
        if (cidr == null) {
            return false;
        }

        String values[] = cidr.split("/");
        Pattern ipv4Pattern = Pattern
                .compile("(([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\.){3}([01]?\\d\\d?|2[0-4]\\d|25[0-5])");
        Matcher mm = ipv4Pattern.matcher(values[0]);
        if (!mm.matches()) {
            return false;
        }
        if (values.length >= 2) {
            int prefix = Integer.valueOf(values[1]);
            if ((prefix < 0) || (prefix > 32)) {
                return false;
            }
        }
        return true;
    }
}

Related

  1. isIpv4(String ipv4)
  2. isIpV4Address(CharSequence address)
  3. isIPv4Address(final String input)
  4. isIPv4Address(final String input)
  5. isIPv4Address(String ipAddress)
  6. isIpv4Correct(String ipAddress)
  7. isIPv4Format(String ip)
  8. isIPv4Format(String str)
  9. isIPv4LiteralAddress(String src)