tags:

views:

1498

answers:

3

I need to determine if given IP address is from some special network i must authenticate automatically.

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
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
+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
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
@carson: Thanks for the warning. I edited my answer to include this information.
Eddie
+1  A: 

You can also try

boolean inSubnet = (ip & netmask) == (subnet & netmask);

or shorter

boolean inSubnet = (ip ^ subnet) & netmask == 0;
Peter Lawrey