×

Java Programs

Java Practice

Java program to check a given IP address is valid or not

Given/input IP address, we have to check whether it is valid or not.
Submitted by Nidhi, on March 04, 2022

Problem statement

In this program, we will check a given IP address is valid or not using the matches() method by applying regular expression.

Java program to check a given IP address is valid or not

The source code to check a given IP address is valid or not is given below. The given program is compiled and executed successfully.

// Java program to check a given IP address 
// is valid or not

public class Main {
  public static boolean validate(final String ip) {
    String PATTERN = "^((0|1\\d?\\d?|2[0-4]?\\d?|25[0-5]?|[3-9]\\d?)\\.){3}(0|1\\d?\\d?|2[0-4]?\\d?|25[0-5]?|[3-9]\\d?)$";
    return ip.matches(PATTERN);
  }

  public static void main(String[] args) {
    String ip1 = "192.168.10.5";
    String ip2 = "192.1681.10.5";

    if (validate(ip1) == true)
      System.out.println("IP address is valid");
    else
      System.out.println("IP address is not valid");

    if (validate(ip2) == true)
      System.out.println("IP address is valid");
    else
      System.out.println("IP address is not valid");

  }
}

Output

IP address is valid
IP address is not valid

Explanation

In the above program, we created a public class Main. It contain two static methods validate() and main().

The validate() method returns true when the given string contains a valid IP address otherwise it returns false.

The main() method is an entry point for the program. Here, we used the regular expression in matches() method to check a given IP address is valid or not and printed the appropriate message.

Java Basic Programs »



Related Programs



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.