可以像他们在 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库和公共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 已关闭,这是另一个公共 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);
});
});
更多信息https://www.ipify.org/