3

I have running Node.JS & Express application on localhost (127.0.0.1) and I need to find out the current host (domain) without making requests (for cron job that starts when server is created). The server is created this way

   app = express.createServer();
   app.listen(PORT);   

Now I've found following solution

   app.address();

However the host returned by this is 0.0.0.0, port is returned correct so I guess I need to somehow specify the host during the server start. How can I force it to get the correct host? I've tried

  app = express.createServer({host: '127.0.0.1'});

but that doesn't work :(

ladar
  • 5,858
  • 3
  • 26
  • 38
  • The reason you can't get a host before a request is that you can't really know it without one. Your host can be changed by a reverse proxy such as Nginx. Since node very often sits behind these reverse proxies in production environments, it would be a very inaccurate function, therefore it is not there. – Joe Mills Jul 14 '14 at 14:18
  • I am facing the same issue. I am running a `cron` using `node-cron` module, which exports a csv and mails the link to requester's email id. But I am not able to create a link that will work based on the environment. I do not want to hardcode it. – Mohit Bhardwaj Mar 31 '16 at 06:54

4 Answers4

3

http://nodejs.org/docs/latest/api/os.html#os.hostname

os.hostname()

Returns the hostname of the operating system.

Looks like it might be what you're looking for.

thejh
  • 44,854
  • 16
  • 96
  • 107
  • 4
    Thanks, but that's not what I've meant. I'm trying to get host (domain name) like www.foobar.com or IP address (for example 127.0.0.1 for localhost) – ladar Jan 21 '12 at 16:13
  • 3
    maybe I'm missing something, but yours suggestion returns the same as `uname -n` in linux (or computer name in Windows). But the application is running on localhost (127.0.0.1) so I want to get 127.0.0.1 – ladar Jan 23 '12 at 16:24
  • @ladar: Uhm... you want your IPs, not your hostname? – thejh Jan 23 '12 at 17:50
0

Host may be reached by more than one Ip, you can find good example how to get it - at following article Get local IP address in node.js

Oleg Imanilov
  • 2,591
  • 1
  • 13
  • 26
0

You cant. You have to make a request to something like http://whatismyip.org/

But the reason you want it for can be changed. There are some modules that can be used instead of an actual cron job to do what you want.

https://github.com/ncb000gt/node-cron

fent
  • 17,861
  • 15
  • 87
  • 91
  • I'm actually using this module but the function it triggers needs to know the host name to work properly. I'm kind of confused, why is there the `app.address()` if you can't get the host? – ladar Jan 22 '12 at 13:50
-1

Old question, but anyone landing here looking for help, try this:

app.get('ip')

you can get same way port

app.get('port')
Luckylooke
  • 4,061
  • 4
  • 36
  • 49