I need to determine if given IP address is from some special network i must authenticate automatically.
views:
1498answers:
3
A:
You can use the java network interface like so:
Enumeration<NetworkInterface> nets = NetworkInterface.getNetworkInterfaces();
for (NetworkInterface netint : Collections.list(nets)){
Enumeration<InetAddress> inetAddresses = netint.getInetAddresses();
for (InetAddress inetAddress : Collections.list(inetAddresses)) {
//check if inetAddress is from particular address
}
}
trex279
2009-02-23 12:17:57
I don't think that miceuz is asking to see if a given IP address represents a local network interface, so this probably won't help.
Eddie
2009-02-23 17:07:20
+6
A:
Jakarta Commons Net has org.apache.commons.net.util.SubnetUtils
that appears to satisfy your needs. It looks like you do something like this:
SubnetInfo subnet = (new SubnetUtils("10.10.10.0", "255.255.255.128")).getInfo();
boolean test = subnet.isInRange("10.10.10.10");
Note, as carson points out, that Jakarta Commons Net has a bug that prevents it from giving the correct answer in some cases. Carson suggests using the SVN version to avoid this bug.
Eddie
2009-02-23 17:34:50
Be careful using this. There is a bug that will keep it from working correctly. You may want to pull it out of SVN.http://mail-archives.apache.org/mod_mbox/commons-issues/200902.mbox/%3C2039253761.1233796319684.JavaMail.jira@brutus%3E
carson
2009-02-23 18:43:01
@carson: Thanks for the warning. I edited my answer to include this information.
Eddie
2009-02-23 20:29:29
+1
A:
You can also try
boolean inSubnet = (ip & netmask) == (subnet & netmask);
or shorter
boolean inSubnet = (ip ^ subnet) & netmask == 0;
Peter Lawrey
2009-02-23 20:53:57