2
public String validIPAddress(String IP) {3
if (IP.length() == 0) return "Neither";5
if (IP.indexOf(".") >= 0) return validateIPV4(IP);7
if (IP.indexOf(":") >= 0) return validateIPV6(IP);12
private String validateIPV4(String ip) {14
if (ip.charAt(0) == '.' || ip.charAt(ip.length() - 1) == '.') return "Neither";17
String[] component = ip.split("\\.");20
if (component.length != 4) return "Neither";23
for (String comp : component) {24
if (comp.length() == 0 || comp.length() > 3 || (comp.charAt(0) == '0' && comp.length() > 1)) {29
for (char ch : comp.toCharArray()) {30
if (ch < '0' || ch > '9') return "Neither";34
int num = Integer.parseInt(comp);35
if (num < 0 || num > 255) return "Neither";41
private String validateIPV6(String ip) {42
if (ip.charAt(0) == ':' || ip.charAt(ip.length() - 1) == ':') return "Neither";44
String[] component = ip.split(":");46
if (component.length != 8) return "Neither";48
for (String comp : component) {49
if (comp.length() == 0 || comp.length() > 4) return "Neither";51
for (char ch : comp.toLowerCase().toCharArray()) {52
if ((ch < '0' || ch > '9')53
&& (ch != 'a' && ch != 'b' && ch != 'c' && ch != 'd' && ch != 'e' && ch != 'f')) {