# 468. Validate IP Address

[https://leetcode.com/problems/validate-ip-address/](https://leetcode.com/problems/validate-ip-address/)

[https://stackoverflow.com/questions/785586/how-can-split-a-string-which-contains-only-delimiter](https://stackoverflow.com/questions/785586/how-can-split-a-string-which-contains-only-delimiter)

![](https://4272748102-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LekNH5IywF8mjBxFcnu%2F-M9wXyqplgdy7VS232lc%2F-M9wYElPPCt-wbHKuLxK%2Fimage.png?alt=media\&token=115416d4-5781-40c9-a524-a09ce63e4b33)



```java
class Solution {
    public String validIPAddress(String IP) {
        String ipv4[] = IP.split("\\.", -1);
        String ipv6[] = IP.split("\\:", -1);

        if (IP.chars().filter(c -> c == '.').count() == 3 && validateIPv4(ipv4)) {
            return "IPv4";
            
        } else if (IP.chars().filter(c -> c == ':').count() == 7 && validateIPv6(ipv6)) {
            return "IPv6";
        }
        return "Neither";
    }
    
    private boolean validateIPv4(String ip[]) {
        try {
            for (String s : ip) {
                int i = Integer.parseInt(s);
                if (!s.equals(String.valueOf(i)) || !(i >= 0 && i <= 255)) {
                    return false;
                }
            }
        } catch(NumberFormatException e) {
            return false;
        }
        return true;    
    }
    
    private boolean validateIPv6(String ip[]) {
        try {
            for (String s : ip) {
                if (s.length() > 4 || Integer.parseInt(s, 16) < 0 || s.charAt(0) == '-') {
                    return false;
                }
            }
            
        } catch(NumberFormatException e) {
            return false;
        }
        return true;  
    }
}
```
