BM Balmiki Mandal 06 May 2023 22 views 0 comments Core Java

Validate IPv4 Address in 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.

0 Comments

No comments yet, Be the first to comment.

Post a Comment

Please sign in to post a comment.

Related Posts

Unlock the Ins and Outs of JavaScript Engines and Runtimes

What is a JavaScript Engine? A JavaScript engine is a program or interpreter which executes JavaScript code....

BM Balmiki Mandal 05 Sep 2023
Implementing HMACSHA256 Algorithm in Java with Key

Introducing HMACSHA256 in Java with Key HMACSHA256 is an authentication algorithm designed to secure data, su...

BM Balmiki Mandal 30 Aug 2023
HMACSHA256 Java Example - Creating Secure Message Authentication

HMACSHA256 Java Example HMACSHA256 is an advanced encryption algorithm that allows developers to create encry...

BM Balmiki Mandal 30 Aug 2023