Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I detect whether a given IP is in a given subnet in Javascript?

I'd like to write a function in Javascript along the lines of:

in_subnet(ip, network, slash) {
    ...
}

in_subnet('1.2.3.4', '1.2.0.0', 16) # True, since it's in 1.2.0.0/16
in_subnet('1.2.3.4', '1.2.0.0', 24) # False, since it's not in 1.2.0.0/24

Should I write it from scratch, or are there some good libraries I could use? Or is the entire function already written and in the public domain?


1 Answers

Pseudocode, building on dustin's answer:

addr_one = ip_addr_to_integer(ip);
addr_two = ip_addr_to_integer(network);
mask = ((1 << (32-slash)) - 1) ^ 0xFFFFFFFF;
return (((addr_one ^ addr_two) & mask) == 0);

If you know that the IP address strings are valid, you can probably use string.split('.') to get the four octets and easily convert them to an integer.

like image 153
Artelius Avatar answered Jan 27 '26 16:01

Artelius



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!