概述:
使用netty 做DNS解析服务:
源码:
1.使用netty 做一个UDPserver:netty的版本必须大度4.1.x
netty 在4.1.x 加入DNS协议
final NioEventLoopGroup group = new NioEventLoopGroup();
try {
Bootstrap bootstrap = new Bootstrap();
bootstrap.group(group).channel(NioDatagramChannel.class)
.handler(new ChannelInitializer<NioDatagramChannel>() {
@Override
protected void initChannel(NioDatagramChannel nioDatagramChannel) throws Exception {
nioDatagramChannel.pipeline().addLast(new DatagramDnsQueryDecoder());
nioDatagramChannel.pipeline().addLast(new DatagramDnsResponseEncoder());
nioDatagramChannel.pipeline().addLast(new DnsHandler());
}
}).option(ChannelOption.SO_BROADCAST, true);
ChannelFuture future = bootstrap.bind(53).sync();
future.channel().closeFuture().sync();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
group.shutdownGracefully();
}
DatagramserdnsQueryDecoder,datagramDNSResponseEncoder 编解码器大大减少了自己的编解码工作。
二。添加一个hander复写DNS域名服务:hander,channelRead0,根据数据完成:
ublic class DnsHandler extends SimpleChannelInboundHandler<DatagramDnsQuery> {
@Override
public void channelRead0(ChannelHandlerContext ctx, DatagramDnsQuery query) throws UnsupportedEncodingException {
// 假数据,域名和ip的对应关系应该放到数据库中
Map<String, byte[]> ipMap = new HashMap<>();
ipMap.put("www.baidu.com.", new byte[] { 61, (byte) 135, (byte) 169, 125 });
DatagramDnsResponse response = new DatagramDnsResponse(query.recipient(), query.sender(), query.id());
try {
DefaultDnsQuestion dnsQuestion = query.recordAt(DnsSection.QUESTION);
response.addRecord(DnsSection.QUESTION, dnsQuestion);
System.out.println("查询的域名:" + dnsQuestion.name());
ByteBuf buf = null;
if (ipMap.containsKey(dnsQuestion.name())) {
buf = Unpooled.wrappedBuffer(ipMap.get(dnsQuestion.name()));
} else {
// TODO 对于没有的域名采用迭代方式
// buf = Unpooled.wrappedBuffer(new byte[] { 127, 0, 0, 1});
}
// TTL设置为10s, 如果短时间内多次请求,客户端会使用本地缓存
DefaultDnsRawRecord queryAnswer = new DefaultDnsRawRecord(dnsQuestion.name(), DnsRecordType.A, 10, buf);
response.addRecord(DnsSection.ANSWER, queryAnswer);
} catch (Exception e) {
System.out.println("异常了:" + e);
}finally {
本文介绍如何使用Netty框架实现DNS解析服务。通过创建UDP Server并利用Netty 4.1.x版本提供的DNS协议支持,实现了DNS查询的接收与响应。文章提供了核心代码示例,包括编解码器的使用及自定义DNS处理器。
395

被折叠的 条评论
为什么被折叠?



