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...
Step-by-Step Guide
-
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; } -
Step 2: else it returns false.
-
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
Jessica Gordon
Specializes in breaking down complex lifestyle topics into simple steps.
Rate This Guide
How helpful was this guide? Click to rate: