ClientIPParser { String extractIP(String node) { int length = node.length(); int dots = 0; int lastDotIndex = -1; int colons = 0; int lastColonIndex = -1; for (int i = 0; i < length; i++) { char ch = node.charAt(i); if (ch == '.') { dots++; lastDotIndex = i; } else if (ch == ':') { colons++; lastColonIndex = i; } else if (Character.digit(ch, 16) == -1) { throw new BadRequestException("invalid client ip address"); } } if (dots == 0) return node; if (dots == 3 && (colons == 0 || colons == 1 && lastColonIndex > lastDotIndex && lastColonIndex < length - 1)) { if (lastColonIndex > 0) return node.substring(0, lastColonIndex); return node; } throw new BadRequestException("invalid client ip address"); }   public int maxForwardedIPs; }
@Test void extractIP() { assertThat(parser.extractIP("2001:db8:cafe::17")).isEqualTo("2001:db8:cafe::17"); assertThat(parser.extractIP("192.0.2.43:47011")).isEqualTo("192.0.2.43"); assertThat(parser.extractIP("192.0.2.43")).isEqualTo("192.0.2.43"); assertInvalidNode("192.0.2.43:"); assertInvalidNode("192.0:2.43"); assertInvalidNode("192.0.:2.43"); assertInvalidNode("192.0.2:43"); }