Validate an IP address using Regular Expressions in Java

An IPv4 IP Address is a 32-bit number that can be assigned to several devices in a network for identification, communication, etc. In the following tutorial, we will learn how to validate an IP address in Java with the corresponding code.

The validations that an IP address must satisfy are:

  1. All the numbers must be between 0 and 255
  2. The numbers must be spaced using a dot
  3. Cannot have an alphabet
  4. Cannot have a negative number
  5. Repeat 4 times with the exception of the dot

Some examples of valid and invalid IP addresses are:

  1. 10.1.1.0 (Valid)
  2.  10.-255.0.1 (Invalid)
  3. 10..0.1 (Invalid)
  4. 192.168.1.0 (Valid)

We can validate IP addresses using regular expressions. We can use regex in java to validate the addresses. We can form patterns to match the input string using the pattern() and match() classes.

The pattern for an IP address is:  (\\d{1,2}|(0|1)\\” + “d{2}|2[0-4]\\d|25[0-5])” + “\\.”
+ “(\\d{1,2}|(0|1)\\” + “d{2}|2[0-4]\\d|25[0-5])” + “\\.”
+ “(\\d{1,2}|(0|1)\\” + “d{2}|2[0-4]\\d|25[0-5])” + “\\.”
+ “(\\d{1,2}|(0|1)\\” + “d{2}|2[0-4]\\d|25[0-5]

  • /d is used for digits in regular expressions
  • (0|1)\\d{2} checks for a three digit number between 0 and 1
  • \\d{1,2} check for a one or two digit number
  • 2[0-4]\\d|25[0-5] checks for numbers between 200 and 255
  • \\. represents a dot

Java Program to Validate an IP address using Regular Expression in

Below is the Java code for our task:

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

public class ValidateIPAdd {

    public static boolean ValidateIP(String input_IP)
    {
        String numRange = "(\\d{1,2}|(0|1)\\" + "d{2}|2[0-4]\\d|25[0-5])" + "\\." 
              + "(\\d{1,2}|(0|1)\\" + "d{2}|2[0-4]\\d|25[0-5])" + "\\." 
              + "(\\d{1,2}|(0|1)\\" + "d{2}|2[0-4]\\d|25[0-5])" + "\\." 
              + "(\\d{1,2}|(0|1)\\" + "d{2}|2[0-4]\\d|25[0-5])";
        
        Pattern ip_pattern = Pattern.compile(numRange); 
        Matcher match= ip_pattern.matcher(input_IP);
        return match.matches();
    }
    public static void main(String[] args) 
    { 
        String strFalse = "00.500.ip.add";    
        String strTrue = "255.255.255.0";
        
        System.out.println("The Result is:"+ValidateIP(strFalse));
        System.out.println("The Result is:"+ValidateIP(strTrue));
       
    }
}

Output:

The Result is:false
The Result is:true

Leave a Reply

Your email address will not be published. Required fields are marked *