Java InetAddress Check isValidInetAddress(String IP)

Here you can find the source of isValidInetAddress(String IP)

Description

Verify if IP string is an IPv4 address.

License

Open Source License

Parameter

Parameter Description
IP IP to verify

Exception

Parameter Description
IllegalArgumentException an exception

Declaration

public static void isValidInetAddress(String IP) throws IllegalArgumentException 

Method Source Code


//package com.java2s;
/*//www .jav a2s. c  om
 * Copyright (c) 2015-2016 VMware, Inc. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License.  You may obtain a copy of
 * the License at http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software distributed
 * under the License is distributed on an "AS IS" BASIS, without warranties or
 * conditions of any kind, EITHER EXPRESS OR IMPLIED.  See the License for the
 * specific language governing permissions and limitations under the License.
 */

import java.net.InetAddress;
import java.net.UnknownHostException;

public class Main {
    /**
     * Verify if IP string is an IPv4 address.
     *
     * @param IP IP to verify
     * @throws IllegalArgumentException
     */
    public static void isValidInetAddress(String IP) throws IllegalArgumentException {

        // Opened issue #84 to track proper validation
        if (IP == null || IP.isEmpty()) {
            throw new IllegalArgumentException("IP is missing or empty");
        }

        if (IP.contains(":")) {
            // implement IPv6 validation
        } else {
            String[] segments = IP.split("\\.");
            if (segments.length != 4) {
                throw new IllegalArgumentException("IP does not appear valid:" + IP);
            }
            // it appears to be literal IP, its safe to use the getByName method
            try {
                InetAddress.getByName(IP);
            } catch (UnknownHostException e) {
                throw new IllegalArgumentException(e);
            }
        }
    }
}

Related

  1. isValidAddress(InetAddress address, int timeoutMs)
  2. isValidAddress(InetAddress i, boolean includeLocalAddressesInNoderefs)
  3. isValidAddress(InetAddress i, boolean includeLocalAddressesInNoderefs)
  4. isValidCiscoWildcard(InetAddress wildcard)
  5. isValidInetAddress(String address)
  6. isValidInetAddress(String ip)
  7. isValidIntranetAddress(InetAddress address)
  8. isValidIpAddress(InetAddress ip)
  9. isWindowsAutoConfiguredIPv4Address(InetAddress add)