My program gets as input parameter a String containing a list of IP Addresses. Each IP address is separated by a line break. It can look like this:
10.1.1.1 2.2.2.2 11.1.1.1
it can look like this
10.1.1.1-20 1.1.1.1
but it can looki like this
172.16.12.1-20 /24 10.1.1.1
I want to check every IP address and return two Lists validAddresses, invalidAddresses.
I’ve already wrote a program that deals with the first the simplest type of input, i.e. no IP address ranges and no network masks.
private String[] extractIPAddress(String address){
String[] temp;
temp = address.split("\\s+");
return temp;
}
Then I do
addressList = extractIPAddress(String.valueOf(value));
for (int i=0; i < addressList.length; i++) {
if (InetAddresses.isInetAddress(addressList[i]) == true) {
validAddress = validAddress.concat(addressList[i] + '\n');
} else {
invalidAddress = invalidAddress.concat(addressList[i] + '\n');
}
}
Now I’m pondering how to deal with the most complex type of input, esp.
-
when the line has a range attached to it
1.1.1.1-10, how to remove the-10part in order check the main IP address; how to check whether range part-10would make a valid IP address i.e.1.1.1.10and then how to put everything together, so I can return it as a line of thevalidAddressString, looking the same way as at the beginning, i.e.1.1.1.1-10 -
same question applies to the network mask
/24
What elements would this kind of program have? Could you outline it for me?
I thought I would do the following, but I’m not sure if that’s the right way and how to implement some parts:
- if I find a
-then cut off the part starting at the position of-until end of line or “/” (how to do that?) - save that part into the
ipRangevariable - if I find
/then cut off that part starting at the position of/until the end of the line - save that part into
netMaskvariable - copy the content into the
tmp_ipRange = ipRange - remove the
-in thetem_ipRangevariable - replace the last octet of the main IP address with
tmp_ipRange(how to do that?) - add the new IP address to the array created by the
String.split()(impossible, because you can’t just add something to an array in java? what alternative do I have? so I can’t use split here?) - loop through the
addressList(see above code) and check if the IP address is a valid IP address - after the validation add
ipRangeto the mainipAddressifipRangeis notnull(how do I find the mainipAddresstheipRangebelongs to?) - after the validation add
netMasketo the mainipAddress(and range) ifmainAddressis notnull(how do I find the mainipAddressthenetMaskbelongs to?)
OK, I wrote the following code to tackle this task. The code is working as expected. Since this is one of my first java programs at all, I was wondering if you see any issues in this code?: