10

I have a NodeJS express service running on Centos and listens to GET requests and I need to identify the IP of the user.

Currently, I'm using this script

ip = req.headers['x-forwarded-for'] ||
      req.connection.remoteAddress ||
      req.socket.remoteAddress ||
      req.connection.socket.remoteAddress

The problem is that sometimes the IP returned is IPv4 and sometimes it is IPv6. Is there a way to get only IPv4 IPs?

Avi L
  • 1,558
  • 2
  • 15
  • 33
  • 3
    If a user connects via IPv6, there will simply not be an IPv4 address. Your code must be able to handle IPv6 addresses. – Michael Hampton Jul 06 '18 at 14:52
  • That is a very useful comment, I use the solution of @feiiiii but still see some user ips in the ipv6 form. – Dev Ze Apr 20 '20 at 13:32

1 Answers1

19

Update

Base on Micheal's comment, if client is connected via ipv6 there will not be an ipv4 address, so you must be ready to accept ipv6.

specify ipv4 when you listen on the server see doc

.listen(port, '0.0.0.0');
feiiiiii
  • 1,480
  • 1
  • 12
  • 27
  • The doc seems to explain a different behaviour: "If the hostname is omitted, the server will accept connections on any IPv6 address (::) when IPv6 is available, or any IPv4 address (0.0.0.0) otherwise. Omit the port argument, or use a port value of 0, to have the operating system assign a random port, which can be retrieved by using server.address().port after the 'listening' event has been emitted." – Avi L Jun 28 '18 at 07:18
  • It might be useful to add @michael hamptons comment in this answer. For me this wasn't obvious. – Dev Ze Apr 20 '20 at 13:33