-2

I am trying to come up with a regular expression (for use with Java) that captures everything in a line except a list of IP addresses (17 at present). This is being done to verify that the configuration on a network device does not permit any IP address other than the allowed list.

The relevant text of the configuration should look like:

allowed-addresses { 1.1.1.1/32 2.2.2.2/28 3.3.3.3/27 }

I want to capture the extra addresses if the configuration is as below:

allowed-addresses { 1.1.1.1/32 2.2.2.2/28 3.3.3.3/27 4.4.4.4/12 ALL }

The desired expression should capture "4.4.4.4/32 ALL" from the line above.

Epicblood
  • 1,167
  • 2
  • 10
  • 29
  • 1
    Do you actually mean `4.4.4.4/12 ALL` and not `4.4.4.4/32 ALL`? – Dave Bennett Feb 12 '15 at 05:09
  • Is the first configuration `allowed-addresses{..}` the list of allowed ip-addr and the second `allowed-addresses{..}` , the actual configuration file that you are checking against? – Hedge7707 Feb 12 '15 at 05:11
  • do you want to just verify that a string does not contain any of the restricted IPs? – Bohemian Feb 12 '15 at 05:14
  • Why do you want to solve this with regex? A simple parser which has a list of allowed addresses would seem much simpler, and would extend nicely to accept 2.2.2.2/29 as an allowed subset of 2.2.2.2/28 if you should want or need that. – tripleee Feb 12 '15 at 05:41

1 Answers1

0

In my opinion parsing the config file and comparing each white-listed IP-address to the resulting list would have been the easier and time efficient way to go about solving the problem.

However, The following regular expression should take all unapproved IP's and place them into a list. Be very careful when adding the rest of the allowed IP's because if a whitespace is accidentally inserted where it shouldn't be the Regex wont work. Also if the config file isn't spaced exactly as your example, the regex wont match. ( Yet another to take the parsing approach).

import java.util.regex.Pattern;
import java.util.regex.Matcher;
import java.util.ArrayList;

public class IpReg{

    public static void main(String []args){
        ArrayList<String> searchedIps = new ArrayList<String>();
        String config = "allowed-addresses { 1.1.1.1/32 2.2.2.2/28 3.3.3.3/27 4.4.4.4/12 ALL }";

        //To add all 17 ip address you would need to manually add them to the regex below
       Pattern whiteList =  Pattern.compile("[^ ]+ (?<!allowed-addresses |\\{ |\\} | 1\\.1\\.1\\.1/32 |2\\.2\\.2\\.2/28 |3\\.3\\.3\\.3/27 )");


        Matcher w = whiteList.matcher(config);

        while(w.find()){

             System.out.println(w.group(0));
             //use this list to check for ips that arent allowed
             searchedIps.add(w.group(0));

        }
     }
}
Hedge7707
  • 557
  • 1
  • 5
  • 17