Encodes a domain name using DNS encoding, as described here and returns it as a byte array. - Java File Path IO

Java examples for File Path IO:Byte Array

Description

Encodes a domain name using DNS encoding, as described here and returns it as a byte array.

Demo Code


//package com.java2s;

import java.util.StringTokenizer;

public class Main {
    public static void main(String[] argv) throws Exception {
        String domainName = "java2s.com";
        System.out.println(java.util.Arrays
                .toString(encodeDomainName(domainName)));
    }//from  w  w w  .j  a  v a 2  s . c om

    /**
     * Encodes a domain name using DNS encoding, as described
     * <a href="http://www.tcpipguide.com/free/t_DNSNameNotationandMessageCompressionTechnique.htm">here</a> and
     * returns it as a byte array.
     *
     * @param domainName
     * @return Encoded domain name
     */
    public static byte[] encodeDomainName(String domainName) {

        byte[] result = new byte[domainName.length() + 2];
        int position = 0;
        StringTokenizer tokenizer = new StringTokenizer(domainName, ".@");

        while (tokenizer.hasMoreTokens()) {
            String token = tokenizer.nextToken();
            result[position] = (byte) token.length();
            position++;
            for (byte b : token.getBytes()) {
                result[position] = b;
                position++;
            }
        }

        result[position] = (byte) 0;
        return result;
    }
}

Related Tutorials