Node.js:ドメイン名からIPアドレスを取得する
dns モジュールを使用する場合
code:js
const dns = require("dns");
const dnsPromises = dns.promises;
const options = { all: true }; // all: false がデフォルト。どれか1件のみ返ってくる。all: true にすると配列で返ってくる。
dnsPromises.lookup(process.argv2, options).then((addrs) => { addrs.forEach((addr) => {
console.log(addr)
} );
} );
code:console
$ node index.js www.example.com
{ address: '93.184.215.14', family: 4 }
{ address: '2606:2800:21f:cb07:6820:80da:af6b:8b2c', family: 6 }
# 見つからない場合は Error で例外となる。
$ node index.js notexists.example.com
node:internal/errors:563
ErrorCaptureStackTrace(err);
^
Error: getaddrinfo ENOTFOUND notexists.example.com
at GetAddrInfoReqWrap.onlookupall as oncomplete (node:internal/dns/promises:95:17) { errno: -3008,
code: 'ENOTFOUND',
syscall: 'getaddrinfo',
hostname: 'notexists.example.com'
}
Node.js v20.11.1
オプションで何も指定しないと悲惨なことになる。(IPv4かIPv6のどちらが返ってくるかランダムで分からない)
code:index2.js
const dns = require("dns");
const dnsPromises = dns.promises;
const options = {};
dnsPromises.lookup(process.argv2, options).then((...args) => { console.log(...args);
} );
code:js
$ node index2.js www.example.com
{ address: '93.184.215.14', family: 4 }
$ node index2.js localhost
{ address: '::1', family: 6 }
Keyword: 名前解決