Last active
January 2, 2017 15:37
-
-
Save camilajenny/257c2aa50a89161d493ca2d259b84d3e to your computer and use it in GitHub Desktop.
validate IPv4 address
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.InputMismatchException; | |
import java.util.Scanner; | |
import java.util.regex.*; | |
public class IPv4Validator { | |
private String ipv4; | |
private final String IPv4Regex = "\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}"; | |
IPv4Validator(String ipv4) { | |
this.ipv4 = ipv4; | |
} | |
public boolean isValid() { | |
return isPatternValid() && AreNumbersValid(); | |
} | |
private boolean isPatternValid() { | |
boolean isPatternValid = false; | |
try { | |
isPatternValid = Pattern.matches(IPv4Regex, ipv4); | |
} catch (PatternSyntaxException e) { | |
System.out.print(e.getMessage()); | |
} | |
return isPatternValid; | |
} | |
private boolean AreNumbersValid() { | |
Scanner scanner = null; | |
try { | |
scanner = new Scanner(ipv4).useDelimiter(Pattern.compile("\\.")); | |
for (int i : new int[]{1, 2, 3, 4}) { | |
int octet = scanner.nextInt(); | |
if (octet < 0 || octet > 256) { | |
System.out.println(toOrdinal(i) + " number is wrong"); | |
return false; | |
} | |
} | |
} catch (InputMismatchException e) { | |
System.out.println(e.getMessage()); | |
} finally { | |
if(scanner != null) | |
scanner.close(); | |
} | |
return true; | |
} | |
private String toOrdinal(int i) { | |
switch (i) { | |
case 1: return "1st"; | |
case 2: return "2nd"; | |
case 3: return "3rd"; | |
default: return Integer.toString(i) + "th"; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment