提示:您可在线编辑运行本教程的实例 - 运行实例,去试试!
使用DNS编码对域名进行编码,如下所述,并将其作为字节数组返回。
//package com.nowjava; /* *来 自 NowJava.com */ import java.util.StringTokenizer; public class Main { public static void main(String[] argv) throws Exception { String domainName = "nowjava.com"; System.out.println(java.util.Arrays .toString(encodeDomainName(domainName))); } /** * 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();/* 来自 N o w J a v a . c o m*/ result[position] = (byte) token.length(); position++;