/** * Takes a specific IP address or a range specified using the IP/Netmask (e.g. * 192.168.1.0/24 or 202.24.0.0/14). * * @param ipAddress the address or range of addresses from which the request must * come. */ public IpAddressMatcher(String ipAddress) { if (ipAddress.indexOf('/') > 0) { String[] addressWithMask = ipAddress.split("\\/"); ipAddress = addressWithMask[0]; this.bitMask = Integer.parseInt(addressWithMask[1]); } else { bitMask = -1; } this.ipAddress = parseAddress(ipAddress); }
@Test public void testIpRangeMatcher() { Assert.assertTrue(new IpAddressMatcher("192.168.10.110").matches("192.168.10.110")); Assert.assertTrue(new IpAddressMatcher("192.168.1.0/8").matches("192.168.10.110")); Assert.assertTrue(new IpAddressMatcher("192.168.1.0/24").matches("192.168.1.100")); Assert.assertFalse(new IpAddressMatcher("192.168.1.0/24").matches("193.168.1.10")); Assert.assertFalse(new IpAddressMatcher("192.168.1.0/24").matches("192.168.2.10")); Assert.assertFalse(new IpAddressMatcher("192.168.1.0/24").matches("192.168.2.10")); Assert.assertFalse(new IpAddressMatcher("192.168.1.0/8").matches("193.168.1.10")); Assert.assertFalse(new IpAddressMatcher(Config.KUBERNETES_NO_PROXY).matches("kubernetes.default.svc")); }
private static URL getProxyUrl(Config config) throws MalformedURLException { URL master = new URL(config.getMasterUrl()); String host = master.getHost(); if (config.getNoProxy() != null) { for (String noProxy : config.getNoProxy()) { if (isIpAddress(noProxy)) { if (new IpAddressMatcher(noProxy).matches(host)) { return null; } } else { if (host.contains(noProxy)) { return null; } } } } String proxy = config.getHttpsProxy(); if (master.getProtocol().equals("http")) { proxy = config.getHttpProxy(); } if (proxy != null) { return new URL(proxy); } return null; }
public boolean matches(String addressToCheck) { InetAddress checkAddress = parseAddress(addressToCheck); if(checkAddress == 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; }