How to Validate an IP Address in Java

Using regular expression: The following method with return true is the IP Address is valid, else it returns false., Using split method of String: The method described above can also be written in a simple way as follows public boolean...

3 Steps 1 min read Easy

Step-by-Step Guide

  1. Step 1: Using regular expression: The following method with return true is the IP Address is valid

    public boolean validateIPAddress( String ipAddress ){ final Pattern ipAdd= Pattern.compile("b(?:(?:25|2|??) + "{3}(?:25|2|??)b"); return ipAdd.matcher(ipAddress).matches(); } ,"); if (tokens.length != 4) { return false; } for (String str : tokens) { int i = Integer.parseInt(str); if ((i < 0) || (i > 255)) { return false; } } return true; }
  2. Step 2: else it returns false.

  3. Step 3: Using split method of String: The method described above can also be written in a simple way as follows public boolean validateIPAddress( String ipAddress ) { String[] tokens = ipAddress.split("\\.

Detailed Guide

public boolean validateIPAddress( String ipAddress ){ final Pattern ipAdd= Pattern.compile("b(?:(?:25|2|??) + "{3}(?:25|2|??)b"); return ipAdd.matcher(ipAddress).matches(); } ,"); if (tokens.length != 4) { return false; } for (String str : tokens) { int i = Integer.parseInt(str); if ((i < 0) || (i > 255)) { return false; } } return true; }

About the Author

J

Jessica Gordon

Specializes in breaking down complex lifestyle topics into simple steps.

37 articles
View all articles

Rate This Guide

--
Loading...
5
0
4
0
3
0
2
0
1
0

How helpful was this guide? Click to rate: