views:

112

answers:

2

I have an IPaddress and subnet mask, both in unsigned long; how can I AND both of these and check whether my incoming ipaddress (ip2) belongs to the same subnet or not?

like:

if (ip1 & subnet == ip2 & subnet)
    then same subnet.  
+2  A: 

Use parentheses - the precedence levels are confusing:

if ((ip1 & subnet) == (ip2 & subnet))
    ...

The original code was effectively the same as:

if (ip1 & (subnet == ip2) & subnet)
    ...
Jonathan Leffler
A good compiler should warn about this. GCC does, if invoked with `-Wall`.
Hans W
oops! how can i miss it..:(
Ashish
+1  A: 

Just like you did it:

if ((ip1 & subnet) == (ip2 & subnet))
  printf("same subnet 0%x", subnet);

(just added the () to insure the computation is done in the right order).

filofel