可以像在 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 年更新:使用内置的 http 库和公共 APIhttps://whatismyipaddress.com/api https://whatismyipaddress.com/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);
});
});
--
2022 年更新
ChatGPT 使用 ipify 和 json 编写了更长的示例:*是的,我已经测试过它。https://gist.github.com/unitycoder/745a58d562180994a3025afcb84c1753 https://gist.github.com/unitycoder/745a58d562180994a3025afcb84c1753
更多信息https://www.ipify.org/ https://www.ipify.org/