Friday, April 8, 2011

Does anyone know a java component to check if IP address is from particular network/netmask?

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

From stackoverflow
  • 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
            }
        }
    
    Eddie : 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.
  • 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.

    carson : 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
    Eddie : @carson: Thanks for the warning. I edited my answer to include this information.
  • You can also try

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

    or shorter

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

0 comments:

Post a Comment