How to validate an ip address android

Just something I had to figure out today. Thought I might post it, someone might find use for it. I had to validate ip addresses in an android app I am helping build. Below is the method I used for the validation. The same method will work a java application as well.


public static boolean isIpAddress(String ipAddress) {
        String IPADDRESS_PATTERN = "^([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\." +
                                   "([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\." +
                                   "([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\." +
                                   "([01]?\\d\\d?|2[0-4]\\d|25[0-5])$";
        Pattern pattern = Pattern.compile(IPADDRESS_PATTERN);
        Matcher matcher = pattern.matcher(ipAddress);
        return matcher.matches();
 }

Advertisements