IP

Javascript

Node.js uses the package dns for DNS lookups. The documentation is at Node.js Documentation

IP types

There does not appear to be a specific type for Ip addresses.

Get one DNS address

The following program gets one address, here an IPv6 address IP.js illustrates this:



if (process.argv.length < 3) {
    concole.log('Usage: command hostname')
    process.exit(1)
}
hostname = process.argv[2]

const dns = require('dns');

const options = {
  family: 6,
};
dns.lookup(hostname, options, (err, address, family) =>
  console.log('address: %j family: IPv%s', address, family));

Get all DNS addresses

The following program gets all addresses. IP.js illustrates this:


if (process.argv.length < 3) {
    concole.log('Usage: command hostname')
    process.exit(1)
}
hostname = process.argv[2]

const dns = require('dns');

// When options.all is true, the result will be an Array.
options = {
    all: true
}

dns.lookup(hostname, options, (err, addresses) =>
  console.log('addresses: %j', addresses));
// addresses: [{"address":"2606:2800:220:1:248:1893:25c8:1946","family":6}]

Get all addresses for an interface

This is given using the os.networkInterfaces() function interfaces.js illustrates this:



const os = require('os')

ifaces = os.networkInterfaces()
console.dir(ifaces)


Copyright © Jan Newmarch, jan@newmarch.name
Creative Commons License
" Network Programming using Java, Go, Python, Rust, JavaScript and Julia" by Jan Newmarch is licensed under a Creative Commons Attribution-ShareAlike 4.0 International License .
Based on a work at https://jan.newmarch.name/NetworkProgramming/ .

If you like this book, please contribute using PayPal