Node.js Web Server in Practice: Getting the Public IP
Table of Contents
Preface
In Node.js server development, there are scenarios where you need to get the public IP.
However, the default method for getting the IP in Node.js can only retrieve the local IP,
not the public one. This article explains how to get the public IP.
Getting the Public IP on the Server
Getting the public IP on the server side is fairly straightforward.
In Node.js, you can use the following method:
request.connection.remoteAddress;
However, if you are using a reverse proxy like nginx,
the method above will only return the proxy’s IP.
You can modify the nginx configuration as follows:
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.
}
Then retrieve the actual IP via req.headers:
req.headers["x-real-ip"];
qiao-z
qiao-z is a minimalist Node.js web server framework.
https://qiao-z.vincentqiao.com/#/
In qiao-z, you can easily get the public IP:
req.ip;
qiao-get-ip
There is also a packaged npm module, qiao-get-ip: https://code.insistime.com/#/qiao-get-ip
Usage is simple:
const { getIP } = require("qiao-get-ip");
const ip = await getIP();
It sends requests to the following services,
with a default timeout of 200ms, and returns the fastest response
to get the public 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
Summary
1. How to get the public IP on a Node.js server
2. Using qiao-z to build a server and get the public IP via req.ip, https://qiao-z.vincentqiao.com/#/api/req?id=reqip
3. Using qiao-get-ip to get the public IP, https://code.insistime.com/#/qiao-get-ip
Related Articles
Node.js Web Server in Practice: Using PM2 Cluster Mode to Boost API QPS
Preface: pm2 is a Node.js process management tool. This article introduces pm2 cluster mode and uses it to boost Node.js API QPS.
Node.js Web Server in Practice: API Load Testing with autocannon
Preface: AutoCannon is a Node.js-based API load testing tool. https://www.npmjs.com/package/autocannon
Node.js in Practice: Image Processing
Using sharp for image processing in Node.js — covering common image libraries, installation, format conversion, resizing, and the qiao-img wrapper package.
Node.js in Practice: Downloading Files
Preface: Downloading files is one of the most common features in Node.js, but in practice, file downloading can hide various pitfalls.
Node.js in Practice: Using Robust FS
Preface: The fs module is the most common module in Node.js, but using fs often comes with various unexpected pitfalls.