Java InetAddress Check isOnNetwork(InetAddress host, InetAddress network, byte[] mask)

Here you can find the source of isOnNetwork(InetAddress host, InetAddress network, byte[] mask)

Description

Given an InetAddress instance that specifies a network mask and an InetAddress instance for a specific host figure out whether the host is included in the network mask.

License

Open Source License

Parameter

Parameter Description
host Host address.
network Network address (hint: use getNetwork() method).
mask Raw subnet mask (hint: use getSubnetMask() method).

Declaration

public static boolean isOnNetwork(InetAddress host, InetAddress network, byte[] mask) 

Method Source Code


//package com.java2s;
//License from project: Open Source License 

import java.net.InetAddress;

public class Main {
    /**//from ww w  .j av a  2s.  c  om
     * Given an InetAddress instance that specifies a network mask and an 
     * InetAddress instance for a specific host figure out whether the host is 
     * included in the network mask.
     *
     * @param host Host address.
     * @param network Network address (hint: use getNetwork() method).
     * @param mask Raw subnet mask (hint: use getSubnetMask() method).
     */
    public static boolean isOnNetwork(InetAddress host, InetAddress network, byte[] mask) {

        boolean result = true;
        byte[] hostAddr = host.getAddress();
        byte[] networkAddr = network.getAddress();

        for (int i = 0; i < networkAddr.length; i++) {

            if ((hostAddr[i] & mask[i]) != networkAddr[i]) {
                result = false;
                break;
            }
        }
        return result;
    }
}

Related

  1. isLocalIP(final InetAddress ip1, final InetAddress ip2, final int mask)
  2. isLocalIpAddress(final InetAddress ipAddress)
  3. isLoopbackAddress(InetAddress address)
  4. isLoopbackIp(InetAddress addr)
  5. isMulticastAddress(InetAddress ipAddr)
  6. isPortFree(int port, InetAddress addr)
  7. isPortInUse(InetAddress address, int port, int count)
  8. isPortOpen(InetAddress address, int port)
  9. isPrivate(InetAddress addr)