node 获取请求 ip
// 方法1
function getClientIp(req) {
var ipAddress;
var forwardedIpsStr = req.headers['X-Forwarded-For'];//判断是否有反向代理头信息
if (forwardedIpsStr) {//如果有,则将头信息中第一个地址拿出,该地址就是真实的客户端IP;
var forwardedIps = forwardedIpsStr.split(',');
ipAddress = forwardedIps[0];
}
if (!ipAddress) {//如果没有直接获取IP;
ipAddress = req.connection.remoteAddress;
}
return ipAddress;
};
// 方法2
function getClientIp2(req) {
return req.headers['x-forwarded-for'] ||
req.connection.remoteAddress ||
req.socket.remoteAddress ||
req.connection.socket.remoteAddress;
};
const http = require('http')
const server = http.createServer()
//获取客户端真实ip
function getClientIp(req) {
return req.headers['x-forwarded-for'] ||
req.connection.remoteAddress ||
req.socket.remoteAddress ||
req.connection.socket.remoteAddress;
};
server.on('request',(req, res) => {
const url = req.url;
const method = req.method;
const str = `您请求的地址:${url},请求方法:${method}`
// 设置请求头,解决中文乱码问题
res.setHeader('Content-Type','text/html;charset=utf-8')
res.write('ip', 'utf8', () => {
console.log('ippp', getClientIp(req))
})
// 发送数据给客户端和结束请求
res.end(str)
})
server.listen('81',() => {
console.log('start')
})
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
上次更新: 2024/01/30, 00:35:17
- 01
- Node与GLIBC_2.27不兼容解决方案08-19
- 02
- Git清空本地文件跟踪缓存08-13