Here's the scenario... I have a table of subnets. (see below) I have an ip address. I would like to find out what subnet the ip address belongs to based on a lookup in the table. This association will then be used to determine what location the user is at. It's a private network space so the standard internet to location lookups wouldn't apply. What would be the best approach? Would I need to break the ip address into it's numeric parts and to a bitwise comparison against all the subnets.. or are there built-in tools in Java API that could make my life easier for comparing IP address to subnet mask?
I'm mainly looking for best way to compare ipaddress to a given subnetmask and determining yes this matches, or no it doesn't.. Optionally. Any tips on how to store the list and search with minimal operations would be appreciated also.
Ideally I'd be doing something similar to this:
List subnetInfo = null;
subnetInfo = findSubnet('192.168.0.1'); //value null if nothing found
....
//return null if nothing found
List findSubnet(String ipaddress) {
List subnetDetails = null;
.... code here ...
return subnetDetails;
}
Table 1: Sample list of subnets
dk-ballerup-gen-off-v411 10.172.80.0/21 NANR-denmark-ballerup-metallbuen66-ground-first-floors-incl-dhcp-(sr14585203)
ae-dubai-ofssl-gen-off-v410 10.172.88.0/24 NANR-arab-emirates-ofssl-iflex-general-office-v410-(sr12781477)
ru-stpetersburg-gen-off-v411 10.172.89.0/24 NANR-russia-stpetersburg-general-office-incl-dhcp (bsteinba)
Considering that information, we know the most efficient subnet mask for the network is 255.255. 254.0. The valid host address range for each subnet must be written as two ranges, due to the limitations of writing the addresses as dotted quads.
Using Java's InetAddress Class for IPv4We can check if it falls under the given range. Java's InetAddress class represents an IP address and provides methods to get the IP for any given hostnames. An instance of InetAddress represents the IP address with its corresponding hostname.
One goal of a subnet is to split a large network into a grouping of smaller, interconnected networks to help minimize traffic. This way, traffic doesn't have to flow through unnecessary routs, increasing network speeds. Subnetting, the segmentation of a network address space, improves address allocation efficiency.
Apache Commons Net has a SubnetUtils for this sort of thing, including determining if a given IP address is within a given subnet.
Trivial example:
String[] subnetsMasks = { ... };
Collection<SubnetInfo> subnets = new ArrayList<SubnetInfo>();
for (String subnetMask : subnetsMasks) {
subnets.add(new SubnetUtils(subnetMask).getInfo());
}
String ipAddress = ...;
for (SubnetInfo subnet : subnets) {
if (subnet.isInRange(ipAddress)) {
System.out.println("IP Address " + ipAddress + " is in range " + subnet.getCidrSignature());
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With