NPM酷库:ip,IP地址处理

图片描述

NPM酷库,每天两分钟,了解一个流行NPM库。·

今天我们来了解一个专门用来处理IP地址的库:ip,ip库能够获取本机IP地址、比较、转换、掩码/子网计算等各种和网络IP相关的操作:

const ip = require('ip');

// 获取本机网卡IP
ip.address();

// 比较两个IP是否相同
ip.isEqual('::1', '::0:1'); // true 

// IP 表示格式互转
ip.toBuffer('127.0.0.1') // Buffer([127, 0, 0, 1]) 
ip.toString(new Buffer([127, 0, 0, 1])) // 127.0.0.1 
ip.toLong('127.0.0.1'); // 2130706433 
ip.fromLong(2130706433); // '127.0.0.1' 

// 判断是否是内网IP
ip.isPrivate('127.0.0.1') // true 

// 判断IP版本
ip.isV4Format('127.0.0.1'); // true 
ip.isV6Format('::ffff:127.0.0.1'); // true 

// 掩码计算
ip.fromPrefixLen(24) // 255.255.255.0 
ip.mask('192.168.1.134', '255.255.255.0') // 192.168.1.0 
ip.cidr('192.168.1.134/26') // 192.168.1.128 
ip.not('255.255.255.0') // 0.0.0.255 
ip.or('192.168.1.134', '0.0.0.255') // 192.168.1.255 

// 子网计算
ip.subnet('192.168.1.134', '255.255.255.192');
// { networkAddress: '192.168.1.128', 
//   firstAddress: '192.168.1.129', 
//   lastAddress: '192.168.1.190', 
//   broadcastAddress: '192.168.1.191', 
//   subnetMask: '255.255.255.192', 
//   subnetMaskLength: 26, 
//   numHosts: 62, 
//   length: 64, 
//   contains: function(addr){...} } 

// 子网范围判断
ip.cidrSubnet('192.168.1.134/26').contains('192.168.1.190') // true 

参考资料

https://github.com/indutny/no...

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值