How to use ip

Comprehensive ip code examples:

How to use ip.endsWith:

180
181
182
183
184
185
186
187
188


app.listen(port)


function isLoopback(ip)
{
  return ip == '::1' || ip.endsWith('127.0.0.1')
}

How to use ip.push:

177
178
179
180
181
182
183
184
185
186
//const expireDate = Date.now() + body.TTL * 86400 * 1000
//Asetetaan aika ensiksi 10 minuutiksi ja päivitetään oikea aika sitten vasta kun käyttäjä hyväksyy IP:n
const expireDate = Date.now() + 600 * 1000
const ip = []
ipAddress.forEach(e => { //pusketaan haetut IP:t (string) muotoiltuun objekti-taulukkoon (IPs)
  ip.push(new IPs({
    desc: body.desc,
    ip: e,
    user: user._id,
    expirationDate: expireDate,

How to use ip.delete:

274
275
276
277
278
279
280
281
282
283
    const user = await User.findOne({ _id: userID })
    query = await IPs.find({ _id: { $in: ipIds }, user: user })
  } else {
    query = await IPs.find({ _id: { $in: ipIds }})
  }
  query.forEach(ip => ip.delete())

  response.status(204).end()
} catch (error) {
  response.status(401).json({message:error}).end()

How to use ip.includes:

762
763
764
765
766
767
768
769
770
771
}

async getIPv4Addresses() {
  let ip4s = await exec(`ip addr show dev ${this.name} | awk '/inet /' | awk '{print $2}'`, {encoding: "utf8"}).then((result) => result.stdout.trim()).catch((err) => null) || null;
  if (ip4s)
    ip4s = ip4s.split("\n").filter(l => l.length > 0).map(ip => ip.includes("/") ? ip : `${ip}/32`);
  return ip4s;
}

async getIPv6Addresses() {

How to use ip.indexOf:

15
16
17
18
19
20
21
22
23
24
 * 【::ffff:】
 * @param ip
 * @returns {*|string}
 */
static replacePrefix(ip) {
  return ip.indexOf('::ffff:') > -1 ? ip.replace(/::ffff:/g, '') : '-';
}

/**
 * 获取内网IP

How to use ip.save:

85
86
87
88
89
90
91
92
93
94
  user: user,
  expirationDate: expireDate,
})
try{
  //Tallennetaan ip kantaan
  const savedIP = await ip.save()
  //Palautetaan tallennettu IP
  response.status(201).json(savedIP)
} catch (error) {
  response.status(400).json({message:'IP already taken'}).end()

How to use ip.default:

40
41
42
43
44
45
46
47
48
} = this;
const slashIndex = rHost.indexOf('/');
let isHostMatch = false;

if (slashIndex !== -1 && _net.default.isIP(host)) {
  isHostMatch = _ip.default.cidrSubnet(rHost).contains(host);
} else {
  isHostMatch = rHost === host;
}

How to use ip.isEqual:

375
376
377
378
379
380
381
382
383
384
385
function should_proxy(hostname) {
    const isIp = ip.isV4Format(hostname) || ip.isV6Format(hostname);


    for (const { kind, addr } of no_proxy_list) {
        if (isIp) {
            if (kind === 'IP' && ip.isEqual(addr, hostname)) {
                return false;
            }
            if (kind === 'CIDR' && ip.cidrSubnet(addr).contains(hostname)) {
                return false;

How to use ip.not:

86
87
88
89
90
91
92
93
94
95
pool = pool.replace(/\s+/g, "").replace(/\n\r/g, "");
//console.log(pool, "pool");
let arrayips = pool.split(';').filter(item => {return item != ""});
console.log(arrayips, "arrayips");
let i = 0;
let ipnot = ip.not(mask);
let networkIP = ip.mask(cidr, mask);
let broadcaseIP = ip.or(cidr, ipnot);
console.log(ipnot, networkIP, broadcaseIP);
for (i = 0; i < arrayips.length; i++) {

How to use ip.or:

88
89
90
91
92
93
94
95
96
97
let arrayips = pool.split(';').filter(item => {return item != ""});
console.log(arrayips, "arrayips");
let i = 0;
let ipnot = ip.not(mask);
let networkIP = ip.mask(cidr, mask);
let broadcaseIP = ip.or(cidr, ipnot);
console.log(ipnot, networkIP, broadcaseIP);
for (i = 0; i < arrayips.length; i++) {
    let lineips = arrayips[i].split(',');
    console.log(lineips, "lineips");

How to use ip.cidr:

41
42
43
44
45
46
47
48
49
50
        addr
    };
}

try {
    ip.cidr(addr);
    return {
        kind: 'CIDR',
        addr
    };

How to use ip.fromPrefixLen:

150
151
152
153
154
155
156
157
158
159
//console.log(pool, "pool");
let arrayips = pool.split(';').filter(item => {return item != ""});
console.log(arrayips, "arrayips");
let i = 0;
let str = cidr.split('/');  //网络号+网络段位数
let mask = ip.fromPrefixLen(str[1])        
let ipnot = ip.not(mask);
let networkIP = ip.cidr(cidr);
let broadcaseIP = ip.or(str[0], ipnot);
console.log(ipnot, networkIP, broadcaseIP);

How to use ip.isLoopback:

97
98
99
100
101
102
103
104
105
106
107
  const [, info] = contact;
  const isValidAddr = ip.isV4Format(info.hostname) ||
                      ip.isV6Format(info.hostname) ||
                      ip.isPublic(info.hostname);
  const isValidPort = info.port > 0;
  const isAllowedAddr = ip.isLoopback(info.hostname) ? !!loopback : true;


  return isValidPort && isValidAddr && isAllowedAddr;
};

How to use ip.isPrivate:

122
123
124
125
126
127
128
129
130
131
const host = obj.host;
const uri = obj.uri;
let localIP = null;
let flowDirection = null;

if (iptool.isPrivate(srcIP) && iptool.isPrivate(destIP))
  return;

let intf = sysManager.getInterfaceViaIP(srcIP);
if (intf) {

How to use ip.mask:

87
88
89
90
91
92
93
94
95
96
//console.log(pool, "pool");
let arrayips = pool.split(';').filter(item => {return item != ""});
console.log(arrayips, "arrayips");
let i = 0;
let ipnot = ip.not(mask);
let networkIP = ip.mask(cidr, mask);
let broadcaseIP = ip.or(cidr, ipnot);
console.log(ipnot, networkIP, broadcaseIP);
for (i = 0; i < arrayips.length; i++) {
    let lineips = arrayips[i].split(',');

How to use ip.split:

3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
	    ip = newValue;
		changes=true;
	}
}

var parts = ip.split(".");

   var data = [];
var pos=0;
data[pos++]=1; // Funktion ID

How to use ip.isPublic:

1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
traceroute.trace(value.checkHost || "8.8.8.8", (err, hops, destination) => {
  if (err) {
    this.simpleTxData(msg, {}, err, callback);
  } else {
    let secondStepIp = hops[1] ? hops[1].ip : "";
    let isPublic = iptool.isPublic(secondStepIp);
    this.simpleTxData(msg, { hops: hops, secondStepIp: secondStepIp, isPublic: isPublic, destination: destination }, null, callback);
  }
})
break;

How to use ip.toString:

510
511
512
513
514
515
516
517
518
519
520
521


ra.decode = function (buf, offset) {
  if (!offset) offset = 0


  offset += 2
  var host = ip.toString(buf, offset, 4)
  ra.decode.bytes = 6
  return host
}

How to use ip.toBuffer:

62
63
64
65
66
67
68
69
70

function parseIP(ip) {
    ip = ip.split('/');
    let addr = ip[0], mask = ip[1];
    return {
        ip: IP.toBuffer(addr),
        prefix: parseInt(mask)
    }
}

How to use ip.isV6Format:

243
244
245
246
247
248
249
250
251
252
await exec(`sudo iptables -w -t nat -F ${chain}`).catch((err) => {});
await exec(`sudo ip6tables -w -t nat -F ${chain}`).catch((err) => {});
for (let i in dnsServers) {
  const dnsServer = dnsServers[i];
  let bin = "iptables";
  if (!ipTool.isV4Format(dnsServer) && ipTool.isV6Format(dnsServer)) {
    bin = "ip6tables";
  }
  // round robin rule for multiple dns servers
  if (i == 0) {

How to use ip.isV4Format:

149
150
151
152
153
154
155
156
157
158
} else {
  let cidrParts = val.split("/", 2);
  if (cidrParts.length == 2) {
    let addr = cidrParts[0];
    let mask = cidrParts[1];
    if (ip.isV4Format(addr) && RegExp("^\\d+$").test(mask) && ip.isV4Format(val2)) {
      // try matching cidr subnet iff value in alarm is an ipv4 address and value in exception is a cidr notation
      if (!ip.cidrSubnet(val).contains(val2)) {
        return false;
      }

How to use ip.subnet:

4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
case "secondary": {
  const currentSecondaryInterface = currentConfig.secondaryInterface;
  const updatedConfig = { intf: currentConfig.monitoringInterface2 };
  const ipAddress = intf.ipAddress;
  const subnetMask = intf.subnetMask;
  const ipSubnet = iptool.subnet(ipAddress, subnetMask);
  updatedConfig.ip = ipAddress + "/" + ipSubnet.subnetMaskLength; // ip format is <ip_address>/<subnet_mask_length>
  const mergedSecondaryInterface = Object.assign({}, currentSecondaryInterface, updatedConfig); // if ip2 is not defined, it will be inherited from previous settings
  // redundant entries for backward compatitibility
  mergedSecondaryInterface.ipOnly = ipAddress;

How to use ip.fromLong:

22
23
24
25
26
27
28
29
30
31
    break;
  }
}
if (ret) {
  if (id === 'long') {
    var ipaddr = ip.fromLong(ret[0]);
    console.log(ip.isPrivate(ipaddr) ? 'Private IP:' : 'IP:', ipaddr);
  } else if (id === 'ip') {
    if (ip.isPrivate(ret[0])) {
      console.log('Private IP:', ip.toLong(ret[0]));

How to use ip.toLong:

89
90
91
92
93
94
95
96
97
98
class SysManager {
  constructor() { // loglevel is already ignored
    if (instance == null) {
      log.info('Initializing SysManager')
      rclient.hdel("sys:network:info", "oper");
      this.multicastlow = iptool.toLong("224.0.0.0");
      this.multicasthigh = iptool.toLong("239.255.255.255");
      this.repo = {};
      this.ipIntfCache = new LRU({max: 4096, maxAge: 900 * 1000}); // reduce call to inMySubnets4/6 in getInterfaceViaIP4/6, which is CPU intensive, the cache will be flushed if network info is updated
      this.iptablesReady = false;

How to use ip.cidrSubnet:

4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
mergedSecondaryInterface.ipOnly = ipAddress;
mergedSecondaryInterface.ipsubnet = ipSubnet.networkAddress + "/" + ipSubnet.subnetMaskLength;
mergedSecondaryInterface.ipnet = ipAddress.substring(0, ipAddress.lastIndexOf("."));
mergedSecondaryInterface.ipmask = subnetMask;
if (mergedSecondaryInterface.ip2) {
  const ipSubnet2 = iptool.cidrSubnet(mergedSecondaryInterface.ip2);
  mergedSecondaryInterface.ip2Only = mergedSecondaryInterface.ip2.substring(0, mergedSecondaryInterface.ip2.lastIndexOf('/')); // e.g., 192.168.168.1
  mergedSecondaryInterface.ipsubnet2 = ipSubnet2.networkAddress + "/" + ipSubnet2.subnetMaskLength; // e.g., 192.168.168.0/24
  mergedSecondaryInterface.ipnet2 = mergedSecondaryInterface.ip2.substring(0, mergedSecondaryInterface.ip2.lastIndexOf(".")); // e.g., 192.168.168
  mergedSecondaryInterface.ipmask2 = ipSubnet2.subnetMask; // e.g., 255.255.255.0

How to use ip.address:

905
906
907
908
909
910
911
912
913
914
915
916
    return items;
}


async function discover_virtual_appliance_address(app = config.KUBE_APP_LABEL) {
    const public_ip = await net_utils.retrieve_public_ip();
    if (!public_ip || public_ip === ip_module.address()) {
        return [];
    }


    // Addr rpc services ports.