Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to use nodejs listen multiple ips?

var http = require('http');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Hello World\n');
}).listen(80, '127.0.0.1');
console.log('Server running at http://127.0.0.1:1337/');

So,if I wanna listen to 192.168.1.100,just like this?

var http = require('http');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Hello World\n');
}).listen(80, '127.0.0.1').listen(80,'192.168.1.100');
like image 824
Ryan Yiada Avatar asked Aug 03 '13 13:08

Ryan Yiada


2 Answers

Try this

var http = require('http');
function handler(req, res) {
  res.writeHead(200, {'Content-Type': 'text/plain'});
  res.end('Hello World\n');
};
http.createServer(handler).listen(80, '127.0.0.1');
http.createServer(handler).listen(80, '192.168.1.100');
// or listen to both instead - thx @FlashThunder
// http.createServer(handler).listen(80); 
like image 182
Plato Avatar answered Nov 12 '22 06:11

Plato


As http creates socket, you can't assign list of ips to one socket, that's why you need to create separate http objects for every ip, or use 0.0.0.0 (or simply dont define second parameter) to listen on all available ips.

like image 39
Flash Thunder Avatar answered Nov 12 '22 05:11

Flash Thunder