reverse Map IP Address - Java Network

Java examples for Network:IP Address

Description

reverse Map IP Address

Demo Code


//package com.java2s;
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 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!");
        }//from w ww . j a va  2s .  c o m

        ;
        StringBuffer builder = new StringBuffer();
        if (rawAddress.length == 4) {
            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(".");
                    }
                }
            }
        }

        if (rawAddress.length == 4) {
            return builder.toString() + "." + ARPA_DOMAIN_IPv4;
        } else {
            return builder.toString() + "." + ARPA_DOMAIN_IPv6;
        }
    }
}

Related Tutorials