集册 Java实例教程 反向映射IP地址

反向映射IP地址

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

424
反向映射IP地址


//package com.nowjava;

import java.net.InetAddress;
//时 代 J a v a 公 众 号 - nowjava.com 提 供

public class Main {

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

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


    public static String reverseMapAddress(InetAddress address)

            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!");

        }


        ;

        StringBuffer builder = new StringBuffer();

        if (rawAddress.length == 4) {/** from 时 代 J     a    v  a - nowjava.com**/

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

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

                if (index > 0) {

                    builder.append(".");

                }

            }

        } else {

            int[] nibbles = new int[2];

            for (int index = rawAddress.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) {

                        builder.append(
展开阅读全文