Open In App

Validating IPv4 String in Java

Last Updated : 01 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

The name IPV4 stands for Internet Protocol Version 4. They are the logical addresses that are built into the network layer of the 7 layers. It is a 32-bit address that uniquely and universally defines the connection of a device to the internet.

Example of a String is a Valid IPv4 Address

For example, every computer or router has its public IP address which is unique in the network which means no two devices can have the same public IP on the internet. The address space of IPv4 is 232 or 4,294,967,296. The structure of an IPv4 address is given as follows.

  • We have 4 numbers in the address.
  • The 4 numbers are separated by (.).
  • Every number lies between 0 to 235 that is it can be only 8 bits.

Following are some of the valid IPv4 addresses.

128.149.22.1 , 123.213.211.122

Program to check if a String is a valid IPv4 address in Java

Approach 1:

So, the idea is to separate the strings which are separated by dots in the given string, and then check each obtained string for a valid number. We will perform the following steps to implement this method.

  • Separate the string in an array of strings by using the delimiter as (.).
  • Check if there are exactly 4 parts,if not return false.
  • Then run a loop for each separated string.
  • Convert each string into number.
  • Check whether the number lies in between 0 to 235.
  • If any number goes out of bound return false.
  • If all number gets iterated successfully then return true.

Illustration:

Java




// Java Program to check if a String is a valid IPv4 address 
public class ValidateIPv4 {
  
    public static boolean isValidIPv4(String ip) {
        // Step 1: Separate the given string into an array of strings using the dot as delimiter
        String[] parts = ip.split("\\.");
  
        // Step 2: Check if there are exactly 4 parts
        if (parts.length != 4) {
            return false;
        }
  
        // Step 3: Check each part for valid number
        for (String part : parts) {
            try {
                // Step 4: Convert each part into a number
                int num = Integer.parseInt(part);
  
                // Step 5: Check whether the number lies in between 0 to 255
                if (num < 0 || num > 255) {
                    return false;
                }
            } catch (NumberFormatException e) {
                // If parsing fails, it's not a valid number
                return false;
            }
        }
  
        // If all checks passed, return true
        return true;
    }
  
    public static void main(String[] args) {
        // Example usage
        String ipAddress1 = "128.149.22.1";
        String ipAddress2 = "123.213.211.122";
        String invalidIpAddress = "256.0.0.1";
  
        System.out.println(ipAddress1 + " is a valid: " + isValidIPv4(ipAddress1));
        System.out.println(ipAddress2 + " is a valid: " + isValidIPv4(ipAddress2));
        System.out.println(invalidIpAddress + " is a valid: " + isValidIPv4(invalidIpAddress));
    }
}


Output

128.149.22.1 is a valid: true
123.213.211.122 is a valid: true
256.0.0.1 is a valid: false


Time and Space Complexity:

Time complexity: O(n)
Space complexity: O(n)

Approach 2:

In the second approach, we are going to use is regular expression matching. In this approach we will make a regular expression which depicts the constraints of IPv4 address correctly. Then we will match the input string with the regular expression.

The regular expression that we are going to use if as follows:

"^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\." +
"(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\." +
"(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\." +
"(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$";

In the expression given above:

  • The symbol (^) shows the start of the given string.
  • The symbol (\) is for the dot separator between each part of address.
  • The symbol ($) shows the end of the given string.
  • The part (25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?) Shows one of the four parts of the IPv4 address.

Illustration:

Java




//Java program to check if a String is a valid IPv4 address using 
//Regular Expression
import java.util.regex.Matcher;
import java.util.regex.Pattern;
  
public class ValidateIPv4Regex {
  
    public static boolean isValidIPv4(String ip) {
        // Regular expression for a valid IPv4 address
        String ipv4Pattern = "^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\." +
                             "(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\." +
                             "(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\." +
                             "(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$";
  
        // Compile the regular expression
        Pattern pattern = Pattern.compile(ipv4Pattern);
  
        // Create a matcher with the input IP address
        Matcher matcher = pattern.matcher(ip);
  
        // Check if the matcher finds a match
        return matcher.matches();
    }
  
    public static void main(String[] args) {
        // Example usage
        String ipAddress1 = "128.149.22.1";
        String ipAddress2 = "123.213.211.122";
        String invalidIpAddress = "256.0.0.1";
  
        System.out.println(ipAddress1 + " is a valid: " + isValidIPv4(ipAddress1));
        System.out.println(ipAddress2 + " is a valid: " + isValidIPv4(ipAddress2));
        System.out.println(invalidIpAddress + " is a valid: " + isValidIPv4(invalidIpAddress));
    }
}


Output

128.149.22.1 is a valid: true
123.213.211.122 is a valid: true
256.0.0.1 is a valid: false


Time and Space complexity:

Time complexity: O(n)
Space complexity: O(1)



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads