集册 Java实例教程 获取IP子网掩码数字

获取IP子网掩码数字

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

573
获取IP子网掩码数字
/*来自 时 代 J a v a - N o w J a v a . c o m*/

import java.util.ArrayList;

import java.util.regex.Pattern;


public class Main{

    public static void main(String[] argv) throws Exception{

        int cidr = 2;

        System.out.println(getSubnetMaskNumeric(cidr));

    }

    public static long getSubnetMaskNumeric(final int cidr)

            throws InvalidIPAddressException {


        if (cidr > 32 || cidr < 0)

            throw new InvalidIPAddressException(

                    "CIDR can not be greater than 32");//来自 时代Java


        // starting /24 netmask, in decimal (255.255.255.0)

        long netmask = 4294967040L;


        // calculating and correcting netmask

        if (cidr > 24) {

            for (long i = cidr; i > 24; i--) {

                netmask += (long) (java.lang.Math.pow(2, (32 - i)));

            }

        } else if (cidr < 24) {

展开阅读全文