如何用node.js 获取访问者的公网IP?
顺便问一下,如何用最简单的非异步的方式获取本机ip地址
我给你一个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 } ] }
@jiyinyiyong 你们这些家伙都不看API文档的。。。
@leizongmin 原来0.8加上去了
TJ的superagent都用了
@jiyinyiyong 这个只是获得本地的IP而已。
var ip = req.headers[‘x-forwarded-for’] || req.connection.remoteAddress || req.socket.remoteAddress || req.connection.socket.remoteAddress;
用了 os.networkInterfaces() 依然获取不到 公网 IP 上图:
我去,三年前的讨论啊。 nodejs上的有tcp,有http要看哪一层需要知道访问者的来源IP。 @highsea , os.networkInterfaces 明显是看自己主机的IP情况吧。 5楼的应该像,http这一层。