JS实现根据域名查找IP
· 阅读需 1 分钟
直接上代码了,很简单,有 Node 就可以
const dns = require('dns');
const http = require('http');
const url = require('url');
const server = http.createServer((req, res) => {
// 添加CORS跨域头部信息
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE');
res.setHeader('Access-Control-Allow-Headers', 'Content-Type');
// 判断URL是否以/getIp开始
if (req.url.startsWith('/getIp')) {
// 解析URL获取查询参数
const path = url.parse(req.url, true).query;
console.log(path.domain);
// DNS查询
dns.lookup(path.domain, (err, address, family) => {
if (err) {
res.writeHead(500, {'Content-Type': 'text/plain'});
res.end('获取IP地址时出错。');
console.error('DNS查询时出错:', err);
return;
}
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end(address);
console.log('IP地址:', address);
console.log('IP版本:', family);
});
console.log('有人访问了我们的web服务器。');
} else {
res.writeHead(404, {'Content-Type': 'text/plain'});
res.end('未找到');
}
});
server.listen(3636, () => {
console.log('服务器运行在 http://localhost:3636');
});