get-user-ip
v1.0.3
Published
一个轻量、小巧的Node.js模块,用于检索请求用户的IP地址 | A lightweight, small Node.js module to retrieve the IP address of the requesting user
Downloads
1,175
Maintainers
Readme
Installation
npm install get-user-ip --save
Getting Started
const GetUserIP = require('get-user-ip')
const http = require('http')
const server = http.createServer((req,res)=>{
res.end(GetUserIP(req))
})
server.listen(6870)
// on localhost you'll see 127.0.0.1 if you're using IPv4
// or ::1, ::ffff:127.0.0.1 if you're using IPv6
If there are some special cases, such as the use of CloudFlare
, you can append a second parameter, which is an array so it can contain more than one params
const server = http.createServer((req,res)=>{
// This gives priority to getting headers.cf-connecting-ip, and if it doesn't exist, continue with the default parameters
res.end(GetUserIP(req,['headers.cf-connecting-ip']))
})
How It Works
It looks for a specific header in the request and returns the 0.0.0.0
default if it does not exist
The user IP is determined by the following order
const defaultHeaders = [
'headers.x-client-ip',
'headers.x-real-ip',
'headers.x-forwarded-for', // This header will return multiple IP addresses, Format: (Client IP, Proxy 1 IP, Proxy 2 IP...) So return the first
'connection.remoteAddress',
'socket.remoteAddress',
'connection.socket.remoteAddress'
]