如何用node.js 获取访问者的公网IP?
14 回复
我给你一个function,是目前我的网站正在使用的http://sogego.com
exports.getClientIP = function(req){ var ipAddress; var headers = req.headers; var forwardedIpsStr = headers[‘x-real-ip’] || headers[‘x-forwarded-for’]; forwardedIpsStr ? ipAddress = forwardedIpsStr : ipAddress = null; if (!ipAddress) { ipAddress = req.connection.remoteAddress; } return ipAddress; }
这个方法可以判断你是否使用了nginx和一般情况
@jiyinyiyong @snoopy @a272121742 os.networkInterfaces() 参考这里:http://nodejs.org/api/os.html#os_os_networkinterfaces
Get a list of network interfaces:
{ lo0:
[ { address: '::1', family: 'IPv6', internal: true },
{ address: 'fe80::1', family: 'IPv6', internal: true },
{ address: '127.0.0.1', family: 'IPv4', internal: true } ],
en1:
[ { address: 'fe80::cabc:c8ff:feef:f996', family: 'IPv6',
internal: false },
{ address: '10.0.1.123', family: 'IPv4', internal: false } ],
vmnet1: [ { address: '10.99.99.254', family: 'IPv4', internal: false } ],
vmnet8: [ { address: '10.88.88.1', family: 'IPv4', internal: false } ],
ppp0: [ { address: '10.2.0.231', family: 'IPv4', internal: false } ] }