Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting client hostname in Node.js

is it possible to get hostname in Node.js?

This is how I get client's IP:

var ip = request.header('x-forwarded-for');

So, how do I get client's hostname?

var hostname = request.header('???');

Thanks for reply!

like image 727
Ryan Zygg Avatar asked Nov 23 '10 10:11

Ryan Zygg


People also ask

How do I find my hostname in node?

To get the name or hostname of the OS, you can use the hostname() method from the os module in Node. js. /* Get hostname of os in Node. js */ // import os module const os = require("os"); // get host name const hostName = os.

What is __ filename in node?

The __filename represents the filename of the code being executed. This is the resolved absolute path of this code file. For a main program, this is not necessarily the same filename used in the command line. The value inside a module is the path to that module file.

What is HTTP createServer in node js?

The http. createServer() method turns your computer into an HTTP server. The http. createServer() method creates an HTTP Server object. The HTTP Server object can listen to ports on your computer and execute a function, a requestListener, each time a request is made.


3 Answers

You can use the 'dns' module to do a reverse dns lookup:

require('dns').reverse('12.12.12.12', function(err, domains) {
    if(err) {
        console.log(err.toString());
        return;
    }
    console.log(domains);
});

See: http://nodejs.org/docs/v0.3.1/api/all.html#dns.reverse

like image 150
Prestaul Avatar answered Oct 06 '22 05:10

Prestaul


I think this might help you. That's not exactly the client hostname but the ip address.

function getClientAddress(req) {
  return req.headers['x-forwarded-for'] || req.connection.remoteAddress;
}
like image 44
peleteiro Avatar answered Oct 06 '22 04:10

peleteiro


I think the only way you can do it is like this:

<form method="post" action="/gethostname">
    <label for="hostname">What is your hostname?</label>
    <input type="text" name="hostname" id="hostname">
</form>

But I would suggest you don't really need it, it's not like you can do anything useful with the information. If you just want a string to identify with the user's machine then you can make something up.

If what you're really after is the FQDN then I would suggest it's still not really that useful to you, but for that you need Reverse DNS lookup. If you're on a VPS or similar you can probably configure your box to do this for you, but note that it'll likely take a few seconds so it's not a good idea to do it as part of a response. Also note, you'll not be getting the user's machine's FQDN in most cases but that of their router.

like image 26
robertc Avatar answered Oct 06 '22 05:10

robertc