View Javadoc
1   /*
2    * Copyright 2020 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.example.dns.udp;
17  
18  import java.net.InetSocketAddress;
19  import java.util.concurrent.TimeUnit;
20  
21  import io.netty.bootstrap.Bootstrap;
22  import io.netty.buffer.ByteBufUtil;
23  import io.netty.channel.Channel;
24  import io.netty.channel.ChannelHandlerContext;
25  import io.netty.channel.ChannelInitializer;
26  import io.netty.channel.ChannelPipeline;
27  import io.netty.channel.EventLoopGroup;
28  import io.netty.channel.SimpleChannelInboundHandler;
29  import io.netty.channel.nio.NioEventLoopGroup;
30  import io.netty.channel.socket.DatagramChannel;
31  import io.netty.channel.socket.nio.NioDatagramChannel;
32  import io.netty.handler.codec.dns.DatagramDnsQuery;
33  import io.netty.handler.codec.dns.DatagramDnsQueryEncoder;
34  import io.netty.handler.codec.dns.DatagramDnsResponse;
35  import io.netty.handler.codec.dns.DatagramDnsResponseDecoder;
36  import io.netty.handler.codec.dns.DefaultDnsQuestion;
37  import io.netty.handler.codec.dns.DnsQuery;
38  import io.netty.handler.codec.dns.DnsQuestion;
39  import io.netty.handler.codec.dns.DnsRawRecord;
40  import io.netty.handler.codec.dns.DnsRecord;
41  import io.netty.handler.codec.dns.DnsRecordType;
42  import io.netty.handler.codec.dns.DnsSection;
43  import io.netty.util.NetUtil;
44  
45  public final class DnsClient {
46  
47      private static final String QUERY_DOMAIN = "www.example.com";
48      private static final int DNS_SERVER_PORT = 53;
49      private static final String DNS_SERVER_HOST = "8.8.8.8";
50  
51      private DnsClient() { }
52  
53      private static void handleQueryResp(DatagramDnsResponse msg) {
54          if (msg.count(DnsSection.QUESTION) > 0) {
55              DnsQuestion question = msg.recordAt(DnsSection.QUESTION, 0);
56              System.out.printf("name: %s%n", question.name());
57          }
58          for (int i = 0, count = msg.count(DnsSection.ANSWER); i < count; i++) {
59              DnsRecord record = msg.recordAt(DnsSection.ANSWER, i);
60              if (record.type() == DnsRecordType.A) {
61                  //just print the IP after query
62                  DnsRawRecord raw = (DnsRawRecord) record;
63                  System.out.println(NetUtil.bytesToIpAddress(ByteBufUtil.getBytes(raw.content())));
64              }
65          }
66      }
67  
68      public static void main(String[] args) throws Exception {
69          InetSocketAddress addr = new InetSocketAddress(DNS_SERVER_HOST, DNS_SERVER_PORT);
70          EventLoopGroup group = new NioEventLoopGroup();
71          try {
72              Bootstrap b = new Bootstrap();
73              b.group(group)
74               .channel(NioDatagramChannel.class)
75               .handler(new ChannelInitializer<DatagramChannel>() {
76                   @Override
77                   protected void initChannel(DatagramChannel ch) throws Exception {
78                       ChannelPipeline p = ch.pipeline();
79                       p.addLast(new DatagramDnsQueryEncoder())
80                       .addLast(new DatagramDnsResponseDecoder())
81                       .addLast(new SimpleChannelInboundHandler<DatagramDnsResponse>() {
82                          @Override
83                          protected void channelRead0(ChannelHandlerContext ctx, DatagramDnsResponse msg) {
84                              try {
85                                  handleQueryResp(msg);
86                              } finally {
87                                  ctx.close();
88                              }
89                          }
90                      });
91                   }
92               });
93              final Channel ch = b.bind(0).sync().channel();
94              DnsQuery query = new DatagramDnsQuery(null, addr, 1).setRecord(
95                      DnsSection.QUESTION,
96                      new DefaultDnsQuestion(QUERY_DOMAIN, DnsRecordType.A));
97              ch.writeAndFlush(query).sync();
98              boolean succ = ch.closeFuture().await(10, TimeUnit.SECONDS);
99              if (!succ) {
100                 System.err.println("dns query timeout!");
101                 ch.close().sync();
102             }
103         } finally {
104             group.shutdownGracefully();
105         }
106     }
107 }