集册 Java实例教程 IP子网地址

IP子网地址

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

522
IP子网地址


//package com.nowjava;

import java.net.InetAddress;

import java.net.UnknownHostException;/**来 自 nowjava.com - 时代Java**/


public class Main {

    public static InetAddress subnetAddress(InetAddress address,

            int networkPrefixLength) throws IllegalArgumentException {

        byte[] rawAddress = address.getAddress();

        byte[] newRawAddress = new byte[rawAddress.length];


        int count = 0;

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

            byte octet = 0x00;/*from 时 代 J a v a - N o w J a v a . c o m*/


            if (count < networkPrefixLength) {

                int value;


                for (int bit = 7; bit >= 0; bit--) {

                    value = 0x00;

                    if (count < networkPrefixLength) {

                        value = ((rawAddress[i] >>> bit) & 0x01);

                    }


                    octet |= ((value & 0x01) << bit);

                    count++;

                }

            }

            newRawAddress[i] = octet;

        }


        try {

            return InetAddress.getByAddress(new
展开阅读全文