【fix】 域名解析正常

This commit is contained in:
wujiawei 2025-03-14 21:07:42 +08:00
parent 4690bc85b3
commit cf9438a7da

View File

@ -1,33 +1,79 @@
package org.framework.lazy.cloud.network.heartbeat.dns;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.dns.*;
import lombok.extern.slf4j.Slf4j;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.HashMap;
import java.util.Map;
@Slf4j
public class DnsServerHandler extends SimpleChannelInboundHandler<DatagramDnsQuery> {
private Map<String, String> domainIpMapping = new HashMap<>();
{
domainIpMapping.put("test.wu-framework.cn.", "124.222.152.160");
domainIpMapping.put("www.google.com.hk.", "120.253.253.97");
}
@Override
protected void channelRead0(ChannelHandlerContext ctx, DatagramDnsQuery query) throws Exception {
log.info("query:{}", query);
// 创建DNS响应
DatagramDnsResponse response = new DatagramDnsResponse(query.recipient(), query.sender(), query.id());
// 处理每个查询问题
for (int i = 0; i < query.count(DnsSection.QUESTION); i++) {
DnsQuestion question = query.recordAt(DnsSection.QUESTION, i);
response.addRecord(DnsSection.QUESTION, question);
DefaultDnsQuestion dnsQuestion = query.recordAt(DnsSection.QUESTION);
response.addRecord(DnsSection.QUESTION, dnsQuestion);
DnsRecordType dnsRecordType = dnsQuestion.type();
// 简单示例返回一个固定的A记录
if (question.type() == DnsRecordType.A) {
log.info("dns:{}", dnsQuestion.name());
// log.info("query:{}", query);
String domain = dnsQuestion.name();
if (dnsRecordType == DnsRecordType.A) {
String ip = domainIpMapping.get(domain);
if (ip != null) {
log.info("ip:{}", ip);
try {
InetAddress address = Inet4Address.getByName(ip);
DefaultDnsRawRecord answer = new DefaultDnsRawRecord(
question.name(), DnsRecordType.A, 3600,
io.netty.buffer.Unpooled.wrappedBuffer(new byte[]{127, 0, 0, 1}));
}
domain, DnsRecordType.A, 3600,
Unpooled.wrappedBuffer(address.getAddress())
);
response.addRecord(DnsSection.ANSWER, answer);
} catch (UnknownHostException e) {
e.printStackTrace();
}
// 发送响应
ctx.writeAndFlush(response);
} else {
// 使用系统默认 DNS 解析
try {
java.net.InetAddress[] addresses = java.net.InetAddress.getAllByName(domain);
for (java.net.InetAddress address : addresses) {
log.info("使用本地dns解析域名{} ip:{}", domain, address.getHostAddress());
response.addRecord(DnsSection.ANSWER, new DefaultDnsRawRecord(
domain, DnsRecordType.A, 3600, Unpooled.wrappedBuffer(address.getAddress())));
}
ctx.writeAndFlush(response);
} catch (Exception e) {
e.printStackTrace();
}
}
} else {
log.info("type:{}", dnsRecordType.name());
}
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {