How To Validate IP Address In Java ?

Many times we ask users to give some details and we need to validate them before moving ahead with our business logic and one of that is IP Address.
In this article we will see how to validate IP Address In Java using Regular Expression. We will validate IPv4 only and that is 32 bit and range is between 0 to 255.

We will validate some valid and invalid scenarios so that you will get better idea on how to Validate IP Address in Java using Regular Expression.

Regular Expression makes our work very easy. To understand this we will first validate IP Address using Regular Expression and then we will validate manually for better understanding.

So below is complete code for IP Validation In Java using Regular Expression.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
package com.example.regex;

import java.util.regex.Pattern;

public class IpAddressValidation {

 public static void main(String[] args) {
  // 127.0.0.1
  System.out.println(IpAddressValidation.isValidIpManually("127.0.0.1"));
 }
 
 public static boolean isValidIp (String ipAddress) {
  
  if (ipAddress == null || ipAddress.isEmpty()) {
   return false;
  }
  
  // 0 to 255
  String digitRegEx = "(\\d{1,2}|(0|1)\\d{2}|2[0-4]\\d|25[0-5])";
  
  String ipRegEx = digitRegEx + "\\." +
    digitRegEx + "\\." +
    digitRegEx + "\\." +
    digitRegEx;
  
  Pattern pattern = Pattern.compile(ipRegEx);
  
  return pattern.matcher(ipAddress).matches();
 }
 
 public static boolean isValidIpManually (String ipAddress) {
  
  if (ipAddress == null || ipAddress.isEmpty()) {
   return false;
  }
  
  String[] strArray = ipAddress.split("\\.");
  
  if (strArray.length != 4) {
   return false;
  }
  
  for (String str : strArray) {
   try {
    Integer num = Integer.valueOf(str);
    
    if (num > 255) {
     return false;
    }
   } catch (NumberFormatException e) {
    return false;
   }
  }
  return true;
 }
}

Output

true


Checkout Below Useful Courses :-


0 Comments