通过NodeJS Express仅获取IPv4 ips [英] Get only IPv4 ips via NodeJS express

查看:521
本文介绍了通过NodeJS Express仅获取IPv4 ips的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 Centos NodeJS express 服务>并监听GET请求,我需要识别用户的IP。

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

问题是有时返回的IP是IPv4有时是IPv6。有没有办法只获取IPv4 IP?

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

推荐答案

更新

根据Micheal的评论,如果客户端通过ipv6连接,则不会有ipv4地址,因此您必须准备好接受ipv6。

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.

在服务器上侦听时指定ipv4,请参见 doc

specify ipv4 when you listen on the server see doc

.listen(port, '0.0.0.0');

这篇关于通过NodeJS Express仅获取IPv4 ips的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆