7

Looking for a string to pass to String#matches(String) that will match IPv4, and another to match IPv6.

Kevin Wong
  • 14,656
  • 11
  • 42
  • 52
  • See also http://stackoverflow.com/questions/53497/regular-expression-that-matches-valid-ipv6-addresses – Flow Jan 25 '17 at 11:52

6 Answers6

18
public static final String IPV4_REGEX = "\\A(25[0-5]|2[0-4]\\d|[0-1]?\\d?\\d)(\\.(25[0-5]|2[0-4]\\d|[0-1]?\\d?\\d)){3}\\z";
public static final String IPV6_HEX4DECCOMPRESSED_REGEX = "\\A((?:[0-9A-Fa-f]{1,4}(?::[0-9A-Fa-f]{1,4})*)?) ::((?:[0-9A-Fa-f]{1,4}:)*)(25[0-5]|2[0-4]\\d|[0-1]?\\d?\\d)(\\.(25[0-5]|2[0-4]\\d|[0-1]?\\d?\\d)){3}\\z";
public static final String IPV6_6HEX4DEC_REGEX = "\\A((?:[0-9A-Fa-f]{1,4}:){6,6})(25[0-5]|2[0-4]\\d|[0-1]?\\d?\\d)(\\.(25[0-5]|2[0-4]\\d|[0-1]?\\d?\\d)){3}\\z";
public static final String IPV6_HEXCOMPRESSED_REGEX = "\\A((?:[0-9A-Fa-f]{1,4}(?::[0-9A-Fa-f]{1,4})*)?)::((?:[0-9A-Fa-f]{1,4}(?::[0-9A-Fa-f]{1,4})*)?)\\z";
public static final String IPV6_REGEX = "\\A(?:[0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}\\z";

Got these from some blog. Someone good w/ regexes should be able to come up with a single regex for all IPv6 address types. Actually, I guess you could have a single regex that matches both IPv4 and IPv6.

Kevin Wong
  • 14,656
  • 11
  • 42
  • 52
  • 6
    Yes, no doubt someone should come up with a single, all encompassing regex -- these are far, far too short as is. – Will Hartung Jul 31 '09 at 06:34
  • Thanks! These are a good starting point. But I've found that IPV6_HEXCOMPRESSED_REGEX will accept "1::2:3:4:5:6:7:8", which isn't valid since you can't have more than 8 groupings and :: implies more compressed groupings. – gusterlover6 Oct 02 '09 at 20:40
6

Another good option for processing IPs is to use Java's classes Inet4Address and Inet6Address, which can be useful in a number of ways, one of which is to determine the validity of the IP address.

I know this doesn't answer the question directly, but just thought it's worth mentioning.

Yuval
  • 7,987
  • 12
  • 40
  • 54
3

Here's a regex to match IPv4 addresses:

\b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b

You'll need to escape the backslashes when you specify it as a string literal in Java:

"\\b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\b"
hasseg
  • 6,787
  • 37
  • 41
1
package com.capgemini.basics;

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

public class Main {
    private static Pattern VALID_IPV4_PATTERN = null;
    private static Pattern VALID_IPV6_PATTERN1 = null;
    private static Pattern VALID_IPV6_PATTERN2 = null;
    private static final String ipv4Pattern = "(([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\.){3}([01]?\\d\\d?|2[0-4]\\d|25[0-5])";
    private static final String ipv6Pattern1 = "([0-9a-f]{1,4}:){7}([0-9a-f]){1,4}";
    private static final String ipv6Pattern2 = "^((?:[0-9A-Fa-f]{1,4}(?::[0-9A-Fa-f]{1,4})*)?)::((?:[0-9A-Fa-f]{1,4}(?::[0-9A-Fa-f]{1,4})*)?)$";


    static {
        try {
            VALID_IPV4_PATTERN = Pattern.compile(ipv4Pattern, Pattern.CASE_INSENSITIVE);
            VALID_IPV6_PATTERN1 = Pattern.compile(ipv6Pattern1, Pattern.CASE_INSENSITIVE);
            VALID_IPV6_PATTERN2 = Pattern.compile(ipv6Pattern2, Pattern.CASE_INSENSITIVE);
        } catch (PatternSyntaxException e) {
            System.out.println("Neither");
        }
    }

    public static List<String> validateAddresses(List<String> ipAddress) {
        final List<String> validity= new ArrayList<String>();
        int len = ipAddress.size();
        for(int i=0; i<len; i++){
            Matcher m1 = Main.VALID_IPV4_PATTERN.matcher(ipAddress.get(i));
            Matcher m12 = Main.VALID_IPV6_PATTERN1.matcher(ipAddress.get(i));
            Matcher m22 = Main.VALID_IPV6_PATTERN2.matcher(ipAddress.get(i));
            if (m1.matches()) {
                validity.add("IPv4");
            }
            else if(m12.matches() || m22.matches()){
                validity.add("IPv6");
            }
            else{
                validity.add("Neither");
            }
        }
        return validity;

    }

    public static void main(String[] args)
    {
        final List<String> IPAddress = new ArrayList<String>();
        //Test Case 0
        /*IPAddress.add("121.18.19.20");
        IPAddress.add("0.12.12.34");
        IPAddress.add("121.234.12.12");
        IPAddress.add("23.45.12.56");
        IPAddress.add("0.1.2.3");*/

        //Test Case 1
        /*IPAddress.add("2001:0db8:0000:0000:0000:ff00:0042:8329");
        IPAddress.add("2001:0db8:0:0:0:ff00:42:8329");
        IPAddress.add("::1");
        IPAddress.add("2001:0db8::ff00:42:8329");
        IPAddress.add("0000:0000:0000:0000:0000:0000:0000:0001");*/

        //Test Case 2
        /*IPAddress.add("000.012.234.23");
        IPAddress.add("666.666.23.23");
        IPAddress.add(".213.123.23.32");
        IPAddress.add("23.45.22.32.");
        IPAddress.add("272:2624:235e:3bc2:c46d:682:5d46:638g");
        IPAddress.add("1:22:333:4444");*/

        final List<String> result = validateAddresses(IPAddress);

        for (int i=0; i<result.size(); i++)
            System.out.println(result.get(i)+" ");

    }

}
0

The regex allows the use of leading zeros in the IPv4 parts.

Some Unix and Mac distros convert those segments into octals.

I suggest using 25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d as an IPv4 segment.

Jason Plank
  • 2,336
  • 5
  • 31
  • 40
Aeron
  • 11
0

Regexes for ipv6 can get really tricky when you consider addresses with embedded ipv4 and addresses that are compressed.

The open-source IPAddress Java library will validate all standard representations of IPv6 and IPv4 and also supports prefix-length (and validation of such). Disclaimer: I am the project manager of that library.

Code example:

try {
    IPAddressString str = new IPAddressString("::1");
    IPAddress addr = str.toAddress();
} catch(AddressStringException e) {
    //e.getMessage has validation error
}
Sean F
  • 4,344
  • 16
  • 30