返回文章列表
Node.js-WebServer开发实践:获取公网IP
Node.js
【前言】
在nodejs server开发实践中,在一些场景下需要获取公网ip,
而nodejs中默认的获取ip的方法,只能获取本地的ip,
而无法获取公网ip,本文介绍如何获取公网ip
【服务端获取公网ip】
在服务端获取公网ip比较简单,
nodejs下可以通过下述方法获取,
request.connection.remoteAddress;
但是如果有使用nginx等代理服务器,
上面的方法只能获取到代理的ip,
可以修改nginx配置,如下
location / {
proxy_pass http://127.0.0.1:9001;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr; # This line.
}
然后通过req.headers获取实际的ip
req.headers['x-real-ip'];
【qiao-z】
qiao-z是一个极简的nodejs web server框架,
https://qiao-z.vincentqiao.com/#/
在qiao-z中可以很方便的获取公网ip
req.ip;
【qiao-get-ip】
封装了一个npm包,qiao-get-ip: https://code.insistime.com/#/qiao-get-ip
使用也很简单
const { getIP } = require('qiao-get-ip');
const ip = await getIP();
这里会请求下面几个服务器地址,
默认设置200ms超时,返回最快的一个,
获取公网ip
- https://api.ipify.org/
- https://icanhazip.com/
- https://ipinfo.io/ip
- https://ifconfig.me/ip
- https://checkip.amazonaws.com/
- http://txt.go.sohu.com/ip/soip
【总结】
1. nodejs服务端获取公网ip的方法
2. 使用qiao-z搭建服务端,通过req.ip获取公网ip, https://qiao-z.vincentqiao.com/#/api/req?id=reqip
3. 使用qiao-get-ip获取公网ip,https://code.insistime.com/#/qiao-get-ip