D
D
dollar2018-10-04 00:13:57
JavaScript
dollar, 2018-10-04 00:13:57

How to check if ip is in given range?

For example, there is a range:

var range = "91.108.56.0/22"; //именно в таком формате

And there is ip: You need to determine if ip is in the range or not.
var ip = "91.108.57.58";

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
dollar, 2018-10-04
@dollar

const ip4ToInt = ip =>
  ip.split('.').reduce((int, oct) => (int << 8) + parseInt(oct, 10), 0) >>> 0;

const isIp4InCidr = ip => cidr => {
  const [range, bits = 32] = cidr.split('/');
  const mask = ~(2 ** (32 - bits) - 1);
  return (ip4ToInt(ip) & mask) === (ip4ToInt(range) & mask);
};

const isIp4InCidrs = (ip, cidrs) => cidrs.some(isIp4InCidr(ip));

isIp4InCidrs('192.168.1.5', ['10.10.0.0/16', '192.168.1.1/24']); // true

A
Andrey Burov, 2018-10-04
@BuriK666

https://stackoverflow.com/questions/19913694/how-c...
Network:

Address:   91.108.56.0          01011011.01101100.001110 00.00000000
Netmask:   255.255.252.0 = 22   11111111.11111111.111111 00.00000000
Wildcard:  0.0.3.255            00000000.00000000.000000 11.11111111
=>
Network:   91.108.56.0/22       01011011.01101100.001110 00.00000000

The address:
Address:   91.108.57.58         01011011.01101100.001110 01.00111010
Netmask:   255.255.252.0 = 22   11111111.11111111.111111 00.00000000
Wildcard:  0.0.3.255            00000000.00000000.000000 11.11111111
=>
Network:   91.108.56.0/22       01011011.01101100.001110 00.00000000
Network - matches, so they are on the same subnet.
Address:   91.108.51.1          01011011.01101100.001100 11.00000001
Netmask:   255.255.252.0 = 22   11111111.11111111.111111 00.00000000
Wildcard:  0.0.3.255            00000000.00000000.000000 11.11111111
=>
Network:   91.108.48.0/22       01011011.01101100.001100 00.00000000
Here the network is different.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question