集册 Java实例教程 给定起始InetAddress和结束InetAddress,计算将用作isOnNetwork()方法掩码的原始子网掩码。

给定起始InetAddress和结束InetAddress,计算将用作isOnNetwork()方法掩码的原始子网掩码。

欢马劈雪     最近更新时间:2020-01-02 10:19:05

489
给定起始InetAddress和结束InetAddress,计算将用作isOnNetwork()方法掩码的原始子网掩码。


//package com.nowjava;

import java.net.InetAddress;

/**
来 自 NowJava.com - 时  代  Java
**/

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 };


    /**

     * 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++) {

        /**来自 
         时 代 J a v a**/

            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
展开阅读全文