如何使用 node.js 获取我的外部 IP 地址?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20273128/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get my external IP address with node.js?
提问by fonini
I'm using node.js and I need to get my external IP address, provided by my ISP. Is there a way to achieve this without using a service like http://myexternalip.com/raw?
我正在使用 node.js,我需要获取我的 ISP 提供的外部 IP 地址。有没有办法在不使用http://myexternalip.com/raw 之类的服务的情况下实现这一目标?
采纳答案by alsotang
use externalippackage
使用externalip包
https://github.com/alsotang/externalip
https://github.com/alsotang/externalip
externalip(function (err, ip) {
console.log(ip); // => 8.8.8.8
});
回答by mgear
Can do the same as what they do in Python to get external IP, connect to some website and get your details from the socket connection:
可以像他们在 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);
});
*Unfortunately cannot find the original Python Example anymore as reference..
*不幸的是,找不到原始的 Python 示例作为参考..
Update 2019:Using built-in http library and public API from https://whatismyipaddress.com/api
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);
});
Tested with Node.js v0.10.48 on Amazon AWS server
在 Amazon AWS 服务器上使用 Node.js v0.10.48 进行测试
回答by jtlindsey
npm install --save public-ipfrom here.
npm install --save public-ip从这里。
Then
然后
publicIp.v4().then(ip => {
console.log("your public ip address", ip);
});
And if you want the local machine ip you can use this.
如果您想要本地机器 ip,您可以使用它。
var ip = require("ip");
var a = ip.address();
console.log("private ip address", a);
回答by Ekin
Edit: This was written back in 2013... The site is gone. I'm leaving the example request code for now unless anyone complains but go for the accepted answer.
编辑:这是在 2013 年写的......该网站已经消失。我暂时离开示例请求代码,除非有人抱怨但去接受已接受的答案。
http://fugal.net/ip.cgiwas similar to that one.
http://fugal.net/ip.cgi与那个类似。
or you can
或者你可以
require('http').request({
hostname: 'fugal.net',
path: '/ip.cgi',
agent: false
}, function(res) {
if(res.statusCode != 200) {
throw new Error('non-OK status: ' + res.statusCode);
}
res.setEncoding('utf-8');
var ipAddress = '';
res.on('data', function(chunk) { ipAddress += chunk; });
res.on('end', function() {
// ipAddress contains the external IP address
});
}).on('error', function(err) {
throw err;
}).end();
Ref: http://www.nodejs.org/api/http.html#http_http_request_options_callback
参考:http: //www.nodejs.org/api/http.html#http_http_request_options_callback
回答by Tyguy7
this should work well without any external dependencies (with the exception of ipify.org):
这应该在没有任何外部依赖的情况下运行良好(ipify.org 除外):
var https = require('https');
var callback = function(err, ip){
if(err){
return console.log(err);
}
console.log('Our public IP is', ip);
// do something here with the IP address
};
https.get({
host: 'api.ipify.org',
}, function(response) {
var ip = '';
response.on('data', function(d) {
ip += d;
});
response.on('end', function() {
if(ip){
callback(null, ip);
} else {
callback('could not get public ip address :(');
}
});
});
You could also use https://httpbin.org
您也可以使用https://httpbin.org
回答by eltoro
You may use the request-ippackage:
您可以使用request-ip包:
const requestIp = require('request-ip');
// inside middleware handler
const ipMiddleware = function(req, res, next) {
const clientIp = requestIp.getClientIp(req);
next();
};
回答by Patrick W. McMahon
node.js has a lot of great built in modules you can use without including any external dependencies. you can make this file.
WhatsMyIpAddress.js
node.js 有很多很棒的内置模块,你可以在不包含任何外部依赖的情况下使用。你可以制作这个文件。
WhatsMyIpAddress.js
const http = require('http');
function WhatsMyIpAddress(callback) {
const options = {
host: 'ipv4bot.whatismyipaddress.com',
port: 80,
path: '/'
};
http.get(options, res => {
res.setEncoding('utf8');
res.on("data", chunk => callback(chunk, null));
}).on('error', err => callback(null, err.message));
}
module.exports = WhatsMyIpAddress;
Then call it in your main.js like this.
然后像这样在你的 main.js 中调用它。
main.js
主文件
const WhatsMyIpAddress = require('./src/WhatsMyIpAddress');
WhatsMyIpAddress((data,err) => {
console.log('results:', data, err);
});
回答by Ade Yahya
Simply use superagent
只需使用超级代理
var superagent = require('superagent');
var getip = function () {
superagent
.get('http://ip.cn/')
.set('User-Agent', 'curl/7.37.1')
.end(function (err, res) {
if (err) {
console.log(err);
}
var ip = res.text.match(/\d+\.\d+\.\d+\.\d+/)[0];
console.log(ip)
// Here is the result
});
};
回答by eisbehr
Another little node module is ext-ip. The difference is, that you can use different response options, matching your coding style. It's ready to use out of the box ...
另一个小节点模块是ext-ip. 不同之处在于,您可以使用不同的响应选项,以匹配您的编码风格。开箱即可使用...
Promise
承诺
let extIP = require('ext-ip')();
extIP.get().then(ip => {
console.log(ip);
})
.catch(err => {
console.error(err);
});
Events
活动
let extIP = require('ext-ip')();
extIP.on("ip", ip => {
console.log(ip);
});
extIP.on("err", err => {
console.error(err);
});
extIP();
Callback
打回来
let extIP = require('ext-ip')();
extIP((err, ip) => {
if( err ){
throw err;
}
console.log(ip);
});
回答by Jacob Morris
You could very easily use an api solution for retrieving the external IP! I made a ip tracker site made for this kinda thing a few days ago! Here is a snippit of code you could use to get IP!
您可以非常轻松地使用 api 解决方案来检索外部 IP!几天前,我为这种事情制作了一个 ip 跟踪器网站!这是您可以用来获取 IP 的代码片段!
async function getIp(cb) {
let output = null;
let promise = new Promise(resolve => {
let http = new XMLHttpRequest();
http.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
output = this.responseText;
resolve("done");
}
}
http.open("GET", "https://iptrackerz.herokuapp.com/ip", true);
http.send();
});
await promise;
if (cb != undefined) {
cb(JSON.parse(output)["ip"]);
} else {
return JSON.parse(output)["ip"];
}
}
Ok, now you have the function getIp()! The way I coded it allows you to do 2 different ways of invoking it! Here they are.
好的,现在你有了 getIp() 函数!我编码它的方式允许您以两种不同的方式调用它!他们来了。
Asynchronous
async function printIP() { let ip = await getIp(); document.write("Your IP is " + ip); }; printIP();
Callback
getIp(ip => { document.write("Your IP is " + ip); });
异步
异步函数 printIP() { let ip = await getIp(); document.write("你的IP是" + ip); }; 打印IP();
打回来
getIp(ip => { document.write("你的 IP 是 " + ip); });

