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?
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 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.
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.
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');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With