CNode

如何用node.js 获取访问者的公网IP?

3342479384发布于14 年前最后回复11 年前17 回复52294 浏览0 收藏

如何用node.js 获取访问者的公网IP?

查看回复

回复 (17)

A
a272121742#2·14 年前
引用 jiyinyiyongrequest.connection.remoteAddress http://stackoverflow.com/questions/8107856/how can i get the us...

顺便问一下,如何用最简单的非异步的方式获取本机ip地址

S
sogego#5·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和一般情况

J
jiyinyiyong#6·14 年前
引用 jiyinyiyongrequest.connection.remoteAddress http://stackoverflow.com/questions/8107856/how can i get the us...

@snoopy 那么多异步的方法, Node 设计得好邪门呐 非异步的话有么?

L
leizongmin#7·14 年前
引用 jiyinyiyongrequest.connection.remoteAddress http://stackoverflow.com/questions/8107856/how can i get the us...

@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 } ] }
L
leizongmin#9·14 年前
J
jiyinyiyong#10·14 年前
引用 jiyinyiyongrequest.connection.remoteAddress http://stackoverflow.com/questions/8107856/how can i get the us...

@leizongmin 表示关于 OS 学得太散, 看过文档很多不懂对应什么

H
highsea#13·11 年前

用了 os.networkInterfaces() 依然获取不到 公网 IP 上图:

63CC3EA5-EB48-4554-894A-F8365842364E.png

S
sioncheng#14·11 年前

我去,三年前的讨论啊。 nodejs上的有tcp,有http要看哪一层需要知道访问者的来源IP。 @highsea , os.networkInterfaces 明显是看自己主机的IP情况吧。 5楼的应该像,http这一层。

A
alsotang#15·12 年前
Y
yaochun#16·12 年前
P
propa-james#17·11 年前

var ip = req.headers['x-forwarded-for'] || req.connection.remoteAddress || req.socket.remoteAddress || req.connection.socket.remoteAddress;

参与回复
登录后即可参与回复。登录