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