reverse IP Subnet Mask Domain - Java Network

Java examples for Network:IP Address

Description

reverse IP Subnet Mask Domain

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 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!");
        }/*ww  w . ja  v  a  2  s .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) {
                        builder.append(".");
                    }
                }
            }
        }

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

Related Tutorials