如何让我的外部IP地址与node.js?
我正在使用node.js,我需要获得我的ISP提供的外部IP地址。 有没有办法实现这一点,而不使用像http://myexternalip.com/raw这样的服务?
http://fugal.net/ip.cgi类似于那个。
或者你可以
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();
参考: http : //www.nodejs.org/api/http.html#http_http_request_options_callback
使用externalip
软件包
https://github.com/alsotang/externalip
externalip(function (err, ip) { console.log(ip); // => 8.8.8.8 });
npm install --save public-ip
从这里保存 npm install --save public-ip
。
然后
publicIp.v4().then(ip => { console.log("your public ip address", ip); });
如果你想要本地机器的ip,你可以使用这个 。
var ip = require("ip"); var a = ip.address(); console.log("private ip address", a);
可以像在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例子作为参考..
这应该工作,没有任何外部依赖(除了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 :('); } }); });
你也可以使用https://httpbin.org
另一个小节点模块是ext-ip
。 不同的是,你可以使用不同的响应选项,匹配你的编码风格。 准备开箱即用…
诺言
let extIP = require('ext-ip')(); extIP.get().then(ip => { console.log(ip); }) .catch(err => { console.error(err); });
活动
let extIP = require('ext-ip')(); extIP.on("ip", ip => { console.log(ip); }); extIP.on("err", err => { console.error(err); }); extIP();
回电话
let extIP = require('ext-ip')(); extIP((err, ip) => { if( err ){ throw err; } console.log(ip); });
我无耻的插件: canihazip ( 披露:我是模块的作者,但不是主页。 )
它可以作为一个模块需要,公开一个单一的函数,可以select传递一个callback函数,它将返回一个承诺。
它也可以全局安装并用作CLI。
简单地使用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 }); };
你可以使用nurl
库命令ippublic
来得到这个。 (披露:我做了nurl)
> npm install nurl-cli -g > ippublic; // 50.240.33.6