Validate IPv4 Address in Java

06 May 2023 Balmiki Mandal 0 Core Java

Validating IPv4 Address in Java

IPv4 addresses are fundamental elements of any TCP/IP networks. They are used to identify each device on the network and must follow certain rules to be considered valid. In Java, it is possible to validate an IPv4 address using regular expressions and some programming logic.

Creating a Regular Expression

Since an IPv4 address consists of four octets (each separated by a period) and each octet can only contain numbers from 0-255, we can create a regular expression (regex) to check for its validity. The regex should check that the string contains four octets, each separated by a period and each containing one to three digits. We can also add a rule to ensure that the first number cannot be zero.

The following regex will satisfy all the requirements: (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]?)){3}

Validation Logic

Once the regex is created, we can use it in our program to validate an IPv4 address. All we need to do is to compile the regular expression and pass the desired string to the matcher() method. If the matcher() method returns true, the string is a valid IPv4 address; otherwise, it is invalid.

Here is a sample program that demonstrates how this can be done:

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

public class IpValidate {

    public static boolean isValid(String ipAddress) {
        String regex = "(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]?)){3}";
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(ipAddress);
        return matcher.matches();
    }

    public static void main(String[] args) {
        System.out.println(isValid("192.168.1.1"));
        System.out.println(isValid("256.168.1.1"));
    }
}

The output of this program will be:

true
false

This shows that the first string is a valid IPv4 address but the second one is not.

BY: Balmiki Mandal

Related Blogs

Post Comments.

Login to Post a Comment

No comments yet, Be the first to comment.