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

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

问题描述

我有一个 NodeJS express 服务在 Centos 上运行并监听 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 ip的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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