IpAddressMatcher { public boolean matches(String addressToCheck) { InetAddress checkAddress = parseAddress(addressToCheck); if(checkAddress == null) { return false; } if (ipAddress == null) { return false; } if (!ipAddress.getClass().equals(checkAddress.getClass())) { return false; } if (bitMask < 0) { return checkAddress.equals(ipAddress); } byte[] checkAddrBytes = checkAddress.getAddress(); byte[] ipAddrBytes = ipAddress.getAddress(); int oddBits = bitMask % 8; int maskBytes = bitMask / 8 + (oddBits == 0 ? 0 : 1); byte[] mask = new byte[maskBytes]; Arrays.fill(mask, 0, oddBits == 0 ? mask.length : mask.length - 1, (byte) 0xFF); if (oddBits != 0) { int lastByte = (1 << oddBits) - 1; lastByte <<= 8 - oddBits; mask[mask.length - 1] = (byte) lastByte; } for (int i = 0; i < mask.length; i++) { if ((checkAddrBytes[i] & mask[i]) != (ipAddrBytes[i] & mask[i])) { return false; } } return true; } IpAddressMatcher(String ipAddress); boolean matches(String addressToCheck);  }
@Test public void testIpRangeMatcher() { assertTrue(new IpAddressMatcher("192.168.10.110").matches("192.168.10.110")); assertTrue(new IpAddressMatcher("192.168.1.0/8").matches("192.168.10.110")); assertTrue(new IpAddressMatcher("192.168.1.0/24").matches("192.168.1.100")); assertFalse(new IpAddressMatcher("192.168.1.0/24").matches("193.168.1.10")); assertFalse(new IpAddressMatcher("192.168.1.0/24").matches("192.168.2.10")); assertFalse(new IpAddressMatcher("192.168.1.0/24").matches("192.168.2.10")); assertFalse(new IpAddressMatcher("192.168.1.0/8").matches("193.168.1.10")); assertFalse(new IpAddressMatcher(Config.KUBERNETES_NO_PROXY).matches("kubernetes.default.svc")); }
@Test public void testIpAddressRegexp() { try { Pattern pattern = Pattern.compile(HttpClientUtils.ipv4Pattern, Pattern.CASE_INSENSITIVE); Matcher matcherPlain = pattern.matcher("192.168.0.1"); assertTrue(matcherPlain.matches()); Matcher matcherPlainProtocol = pattern.matcher("http: assertTrue(matcherPlainProtocol.matches()); Matcher matcherPlainProtocol2 = pattern.matcher("https: assertTrue(matcherPlainProtocol2.matches()); Matcher matcherRange = pattern.matcher("192.168.0.1/24"); assertTrue(matcherRange.matches()); Matcher matcherRangeProtocol = pattern.matcher("http: assertTrue(matcherRangeProtocol.matches()); Matcher matcherRangeProtocol2 = pattern.matcher("https: assertTrue(matcherRangeProtocol2.matches()); } catch (Exception e) { throw new IllegalStateException("Failed to compile pattern."); } }