Java examples for Network:Network Address
Given a starting InetAddress and an ending InetAddress compute a raw subnet mask that will be used as the mask for the isOnNetwork() method.
//package com.java2s; import java.net.InetAddress; public class Main { /** Masks used to get bit values in a byte. */ private static final byte[] BYTE_MASK = { 0x7f, 0x3f, 0x1f, 0x0f, 0x07, 0x03, 0x01, 0x00 };//from www. j a v a 2 s . c om /** * Given a starting InetAddress and an ending InetAddress compute a * raw subnet mask that will be used as the mask for the isOnNetwork() * method. * * We use the following heuristic approach to calculating the subnet mask: * If the bits of the addresses are the same (start[0] = 0 and end[0] = 0; * likewise start[0] = 1 and end[0] = 1), then the corresponding bit * of the subnet mask is 1; otherwise the corresponding bit of the subnet * mask is 0. We evaluate each bit of the start and end addresses until * we find one that is different. After this point, the rest of the * subnet mask is 0 (represents the host part of the subnet mask). * * @param start Starting address. * @param end Ending address. * @return Raw subnet address. */ public static byte[] getSubnetMask(InetAddress start, InetAddress end) { byte[] startAddr = start.getAddress(); byte[] endAddr = end.getAddress(); byte[] maskAddr = new byte[startAddr.length]; for (int i = 0; i < maskAddr.length; i++) { for (int j = 0; j < BYTE_MASK.length; j++) { /* * Flip the bits of the mask (so instead of 0111, we have 1000) * to make the logic easier to follow. */ byte byteMask = (byte) ~BYTE_MASK[j]; byte startAddrMask = (byte) (startAddr[i] & byteMask); byte endAddrMask = (byte) (endAddr[i] & byteMask); if (startAddrMask != endAddrMask) { // End of network part of subnet, rest should already be zeros. return maskAddr; } maskAddr[i] = (byte) (maskAddr[i] | byteMask); } } return maskAddr; } }