View Javadoc
1   /*
2    * Copyright 2018 The Netty Project
3    *
4    * The Netty Project licenses this file to you under the Apache License,
5    * version 2.0 (the "License"); you may not use this file except in compliance
6    * with the License. You may obtain a copy of the License at:
7    *
8    *   https://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12   * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13   * License for the specific language governing permissions and limitations
14   * under the License.
15   */
16  package io.netty.resolver.dns;
17  
18  import java.net.IDN;
19  import java.net.InetAddress;
20  import java.net.UnknownHostException;
21  
22  import io.netty.buffer.ByteBuf;
23  import io.netty.buffer.ByteBufHolder;
24  import io.netty.handler.codec.dns.DnsRawRecord;
25  import io.netty.handler.codec.dns.DnsRecord;
26  
27  /**
28   * Decodes an {@link InetAddress} from an A or AAAA {@link DnsRawRecord}.
29   */
30  final class DnsAddressDecoder {
31  
32      private static final int INADDRSZ4 = 4;
33      private static final int INADDRSZ6 = 16;
34  
35      /**
36       * Decodes an {@link InetAddress} from an A or AAAA {@link DnsRawRecord}.
37       *
38       * @param record the {@link DnsRecord}, most likely a {@link DnsRawRecord}
39       * @param name the host name of the decoded address
40       * @param decodeIdn whether to convert {@code name} to a unicode host name
41       *
42       * @return the {@link InetAddress}, or {@code null} if {@code record} is not a {@link DnsRawRecord} or
43       *         its content is malformed
44       */
45      static InetAddress decodeAddress(DnsRecord record, String name, boolean decodeIdn) {
46          if (!(record instanceof DnsRawRecord)) {
47              return null;
48          }
49          final ByteBuf content = ((ByteBufHolder) record).content();
50          final int contentLen = content.readableBytes();
51          if (contentLen != INADDRSZ4 && contentLen != INADDRSZ6) {
52              return null;
53          }
54  
55          final byte[] addrBytes = new byte[contentLen];
56          content.getBytes(content.readerIndex(), addrBytes);
57  
58          try {
59              return InetAddress.getByAddress(decodeIdn ? IDN.toUnicode(name) : name, addrBytes);
60          } catch (UnknownHostException e) {
61              // Should never reach here.
62              throw new Error(e);
63          }
64      }
65  
66      private DnsAddressDecoder() { }
67  }