1import java.util.regex.Matcher;
2import java.util.regex.Pattern;
3
4// Java program to validate an IPv4 address
5class Main
6{
7 // an IPv4 address
8 private static final String INET4ADDRESS = "172.8.9.28";
9
10 private static final String IPV4_REGEX =
11 "^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\." +
12 "(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\." +
13 "(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\." +
14 "(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$";
15
16 private static final Pattern IPv4_PATTERN = Pattern.compile(IPV4_REGEX);
17
18
19 public static boolean isValidInet4Address(String ip)
20 {
21 if (ip == null) {
22 return false;
23 }
24
25 Matcher matcher = IPv4_PATTERN.matcher(ip);
26
27 return matcher.matches();
28 }
29
30 public static void main(String[] args)
31 {
32 // Validate an IPv4 address
33 if (isValidInet4Address(INET4ADDRESS)) {
34 System.out.print("The IP address " + INET4ADDRESS + " is valid");
35 }
36 else {
37 System.out.print("The IP address " + INET4ADDRESS + " isn't valid");
38 }
39 }
40}