21

I am running a node.js server on port 5403. I can telent to the private ip on this port but cannot telnet to the public ip on the same port.

I assume the cause of this is because node.js is only listening on ipv6. This is the result of

netstat -tpln

(Not all processes could be identified, non-owned process info
will not be shown, you would have to be root to see it all.)
Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address           Foreign Address         State       
PID/Program name
tcp        0      0 127.0.0.1:6379          0.0.0.0:*               LISTEN      
-
tcp        0      0 0.0.0.0:22              0.0.0.0:*               LISTEN      
-
tcp        0      0 127.0.0.1:631           0.0.0.0:*               LISTEN      
-
tcp        0      0 127.0.0.1:5432          0.0.0.0:*               LISTEN      
-
tcp6       0      0 :::5611                 :::*                    LISTEN      
25715/node
tcp6       0      0 :::22                   :::*                    LISTEN      
-
tcp6       0      0 ::1:631                 :::*                    LISTEN      
-
tcp6       0      0 :::5403                 :::*                    LISTEN      
25709/node

How do I make the node server listen on ipv4

codeyard
  • 327
  • 1
  • 2
  • 10

1 Answers1

34

You need to specify an IPV4 address when you call the listen(), I had the same issue with the http module. If I use this:

var http = require('http');

var server = http.createServer(function(request, response) {
...
});

server.listen(13882, function() { });

It only listen on IPV6, as you can see from netstat output:

$ netstat -lntp
Proto  Recv-Q  Send-Q  Local Address  Foreign Address  State
tcp6        0       0  :::13882       :::*             LISTEN

However, if I specify an IPV4 address like this:

var http = require('http');

var server = http.createServer(function(request, response) {
...
});

server.listen(13882, "0.0.0.0", function() { });

netstat will report the server as listening on IPV4:

$ netstat -lntp
Proto  Recv-Q  Send-Q  Local Address     Foreign Address  State
tcp         0       0  0 0.0.0.0:13882   0 0.0.0.0:13882  LISTEN

I'm using Ubuntu 16.04 and npm 5.3.0.

HTH

  • 1
    How about running on both ipv6 and ipv4? – Abhay Jun 21 '20 at 08:24
  • 4
    According to https://nodejs.org/api/net.html#net_server_listen_options_callback by default, the `listen()` will now work on both ipv4 and ipv6. I just tested it via a simple `server.listen(13883, function() { });` and, although `netstat` only reports listening on tcp6, I can connect using also ipv4 addresses like `127.0.0.1` or `192.168.*.*`. I'm now using Ubuntu 18.04 and node v8.12.0 – Dario Fiumicello Jun 22 '20 at 10:11
  • 6
    That only works when you use the `::`. It doesn't work when you specify `0.0.0.0` or `::1` or `127.0.0.1`. I was wondering if it's possible to have net server bind to `::1` and `127.0.0.1` at the same time. – CMCDragonkai Nov 04 '21 at 10:11