Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get only IPv4 ips via NodeJS express

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?

like image 781
Avi L Avatar asked Jun 14 '18 10:06

Avi L


People also ask

How to get client IP address in Node JS?

How to Get Client IP Address in Node JS 1 Create Node JS App 2 Install Express and request-ip Library 3 Create Server.js File 4 Import Request Ip Dependencies in Server.js File. Click to know more about the express. 5 Start Development Server. Node js express get client ip address example. ...

How to get the IP address of a user in express JS?

How to User’s get IP address in Express JS. First, you need to add the following line, if your server is behind a proxy, Add following line in nginx.conf file: and then req.ip for getting user’s ip address and you can also use above code to get ip address here too.

How do I get the IP address from a request object?

There are two main ways to pull the IP address from the request object: using request.connection and using request.header. In addition to the request object, Express also provides a response object as the second argument to the app interface. The response object is used to send information back to the client.


1 Answers

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');
like image 53
feiiiiii Avatar answered Oct 05 '22 23:10

feiiiiii