8

How can I get the FQDN (Fully Qualified Domain Name) of the machine on which node is running?

os.gethostname() is not sufficient, since it usually returns the unqualified DN, only. Same thing for dns.reverse(ip, callback) - assuming the ip is the one associated with the hostname, e.g. obtained using dns.lookup(os.gethostname()[, options], callback).

Also doing a shell.exec("hostname -f", { silent: true }, cb) is not an option, since it is not POSIX compliant and thus will fail e.g. on Solaris et. al., and it is a really bad hack, since exec() is a very, very expensive call wrt. resources like RAM and CPU (causes context switching).

jelmd
  • 349
  • 2
  • 8
  • $(hostname).$(domainname) will work on both Solaris and Linux. But, not only is Solaris POSIX, it's POSIX-certified! It's more POSIX than Linux is. – Will Feb 03 '16 at 21:54
  • 3
    I'm voting to close this question as off-topic because this should have been moved to SO – Anthon May 03 '16 at 05:41

1 Answers1

10

The trick is to utilize the getnameinfo(...) function provided by the OS usually via libc.so or libsocket.so, since it does a FQDN lookup by default! Because dns.lookupService(address, port, callback) seems to be the only documented nodeJS core function, which "wraps" it, we need to use this one. E.g.:

var os = require('os');
var dns = require('dns');

var h = os.hostname();
console.log('UQDN: ' + h);

dns.lookup(h, { hints: dns.ADDRCONFIG }, function(err, ip) {
    console.log('IP: ' + ip);
    dns.lookupService(ip, 0, function (err, hostname, service) {
        if (err) {
            console.log(err);
            return;
        }
        console.log('FQDN: ' + hostname);
        console.log('Service: ' + service);
    });
});

Port 0 is used in the example to show that this has no influence on the result (by default there is no service defined for this port).

jelmd
  • 349
  • 2
  • 8