Filter proxy addresses using SubnetUtils (Apache Commons Net 3.6 API)


Hi, I am Malathi Boggavarapu working at Volvo Group and i live in Gothenburg, Sweden. I have been working on Java since several years and had vast experience and knowledge across various technologies.

This post illustrate how to filter out internal proxy addresses from the real client IP address whereas internal proxy address is represented in the form of CIDR notation in your application

Example of CIDR notation of IP addresses.
10.0.0.0/8 - This represents range of IP addresses from 10.0.0.0 to 10.255.255.255
Try it out at https://mxtoolbox.com/subnetcalculator.aspx

In below example we use SubnetUtils of Apache Common Net 3.6 API to check whether particular IP address is in range of IP addresses which is represented in CIDR notation. We also illsutrate how to use Java 8 stream, Map, Filter along with the Predicate which is passed to Filter.

SubnetUtils have a method called isInRange to check whether the particular IP address is in range of IP addresses. See below.


public static String filteredIpAddresses(){

 String proxyAddresses = "10.0.0.0/8"; // CIDR notation
 String ipAdress = "46.150.151.10, 46.150.151.11";

 Set<String> ipAdresses =                 Arrays.stream(ipAdress.split(",")).map(String::trim).collect(Collectors.toSet())

 Set<String> proxies = Arrays.stream(proxyAddresses.split(",")).map(String::trim).collect(Collectors.toSet())

List<String> filteredIpAddresses
ipAdresses.stream().filter(FilterProxyPredicate.internalProxyAddress(proxies)).collect(Collectors.toList());

return String.join(",", filteredIpAddresses);
}

The following Predicate is passed to the Filter inorder to filter out internal proxy addresses.

public class FilterProxyPredicate(){
    public static Predicate<String> internalProxyAddress(List<String> proxies){
        return proxy -> {
             for(String proxyAddress : proxies){
                   SubnetUtils subnetUtil = new SubnetUtils(proxyAddress);
                   if(subnetUtil.getInfo().isInRange(proxy))
                        return false;
              }
              return true;
       };
    }     
}

Hope the post is helpful. 

Comments

Popular posts from this blog

Bash - Execute Pl/Sql script from Shell script

Gradle Fundamentals

Load Balancing using Spring Cloud Netflix Ribbon