-1

Is there a way to use regular expressions and get a list of IP address? In my case, there are aliases defined with numbers in the system for each device interface and I need to fetch the list using aliases. For test systems, all aliases could map to the same device whereas in production it would differ.

For eg., I can have traffic1, traffic2, traffic3, etc., mapped to eth0, eth1.. so on in production. Where as all trafficX could be mapped to eth0 in tests.

Is there a way get the list of all IP address by passing traffic* or something like that?

Chandru
  • 61
  • 7

1 Answers1

-1

This method reads the /etc/hosts and search a pattern:

private static InetAddress[] listIPs(String re) throws IOException {
    Pattern pat = Pattern.compile(re);
    try (InputStream stream = new FileInputStream("/etc/hosts");
            Reader reader = new InputStreamReader(stream, "UTF-8");
            BufferedReader in = new BufferedReader(reader)) {
        Set<InetAddress> result = new HashSet<>();
        String line = in.readLine();
        while (line != null) {
            String[] fields = line.split("\\s+");
            boolean found = false;
            for (int i = 1; !found && i < fields.length; ++i) {
                found = pat.matcher(fields[i]).matches();
            }
            if (found) {
                result.add(InetAddress.getByName(fields[0]));
            }
            line = in.readLine();
        }
        return result.toArray(new InetAddress[result.size()]);
    }
}    

In your example, you could pass "traffic[0-9]+" for instance.

Maurice Perry
  • 9,261
  • 2
  • 12
  • 24
  • This works, Thanks! I was looking for some standard API in Java SDK that would perform this. Seems no. Anyway thanks again! – Chandru Feb 05 '18 at 15:02