ADVERTISEMENT
ADVERTISEMENT

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 Solution:

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

Program/Source Code:

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 »


ADVERTISEMENT
ADVERTISEMENT


Comments and Discussions!



ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.