Get only IPv4 ips via NodeJS express

允我心安 提交于 2020-06-27 10:01:07

问题


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?


回答1:


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');


来源:https://stackoverflow.com/questions/50855419/get-only-ipv4-ips-via-nodejs-express

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!