IPv4 "in subnet" function

-2

Implement the following JavaScript method as short as possible:

function same_subnet(ip_a,ip_b,sn_mask)
{

}

It should get 2 IP addresses and a subnet mask. It should return true if ip_a and ip_b are in the same subnet.

Example calls:

  1. same_subnet("192.168.0.1","192.168.0.15","255.255.255.0")true
  2. same_subnet("192.168.0.1","192.168.1.15","255.255.0.0")true
  3. same_subnet("192.168.0.1","192.168.1.15","255.255.255.0")false

Chris Tobba

Posted 2013-03-18T20:13:31.310

Reputation: 29

Question was closed 2013-03-18T21:32:02.193

1Could it be any language or just javascript? If just javascript, please add javascript tag! – randomra – 2013-03-18T21:14:21.190

1In other words, implement the isInNet function as used in Proxy Auto-Config (PAC) files, but under a different name, and only accepting an IPv4 address as the "host". – PleaseStand – 2013-03-18T21:17:27.977

Answers

1

126

Fits into a tweet and doesn't even leak globals.

function same_subnet(a,b,c){function x(n){return n=n.split("."),n[0]<<24|n[1]<<16|n[2]<<8|n[3]}return(x(a)&x(c))==(x(b)&x(c))}

copy

Posted 2013-03-18T20:13:31.310

Reputation: 6 466

Looks to me like it leaks the global x. – Peter Taylor – 2013-03-18T21:30:12.000

@PeterTaylor Try again ;-) – copy – 2013-03-18T21:32:36.747

Maybe I've misunderstood or misremembered Crockford's book. – Peter Taylor – 2013-03-18T21:41:53.607