最佳答案
可以像他们在 Python 中做的一样来获取外部 IP,连接到某个网站并从套接字连接中获取您的详细信息:
const net = require('net');
const client = net.connect({port: 80, host:"google.com"}, () => {
console.log('MyIP='+client.localAddress);
console.log('MyPORT='+client.localPort);
});
*很遗憾,无法再找到原始 Python 示例作为引用。
2019 年更新: 使用来自 https://whatismyipaddress.com/api 的内置 http 库和公共(public) API
const http = require('http');
var options = {
host: 'ipv4bot.whatismyipaddress.com',
port: 80,
path: '/'
};
http.get(options, function(res) {
console.log("status: " + res.statusCode);
res.on("data", function(chunk) {
console.log("BODY: " + chunk);
});
}).on('error', function(e) {
console.log("error: " + e.message);
});
在 Amazon AWS 服务器上使用 Node.js v0.10.48 测试
--
2021 年更新
ipv4bot 已关闭,这是另一个公共(public) API:
var http = require('http');
http.get({'host': 'api.ipify.org', 'port': 80, 'path': '/'}, function(resp) {
resp.on('data', function(ip) {
console.log("My public IP address is: " + ip);
});
});
关于Node.js - 如何在 node.js 应用程序中获取我的外部 IP 地址?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20273128/