集册 Java实例教程 反向IP子网掩码域

反向IP子网掩码域

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

440
反向IP子网掩码域


//package com.nowjava;
/**来自 
 N o w J a v a . c o m - 时代Java**/

import java.net.InetAddress;


public class Main {

    public static String ARPA_DOMAIN_IPv4 = "in-addr.arpa.";

    public static String ARPA_DOMAIN_IPv6 = "ip6.arpa.";


    public static String reverseSubnetMaskDomain(InetAddress address,

            int networkPrefixLength) throws IllegalArgumentException {

        byte[] rawAddress = address.getAddress();


        if (rawAddress.length != 4 && rawAddress.length != 16) {

            throw new IllegalArgumentException(

                    "Internet Address must contain either 4 or 16 octets!");

        }
//n o w j a v a . c o m 提 供

        ;

        //        int length = networkPrefixLength / 8;

        int length = rawAddress.length;


        StringBuffer builder = new StringBuffer();

        if (rawAddress.length == 4) {

            for (int index = length - 1; index >= 0; index--) {

                builder.append(rawAddress[index] & 0xFF);

                if (index > 0) {

                    builder.append(".");

                }

            }

        } else {

            int[] nibbles = new int[2];

            for (int index = length - 1; index >= 0; index--) {

                nibbles[0] = (rawAddress[index] & 0x0FF) >> 4;

                nibbles[1] = (rawAddress[index] & 0x0FF) & 0x0F;

                for (int nibbleIndex = nibbles.length - 1; nibbleIndex >= 0; nibbleIndex--) {

                    builder.append(Integer

                            .toHexString(nibbles[nibbleIndex]));

                    if (index > 0 || nibbleIndex > 0) {

                       
展开阅读全文