Ashish
Ashish

Reputation: 328

How to calculate the AND operation of an IPaddress and a subnet mask in C?

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.  

Upvotes: 1

Views: 1503

Answers (2)

filofel
filofel

Reputation: 1378

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).

Upvotes: 1

Jonathan Leffler
Jonathan Leffler

Reputation: 753705

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)
    ...

Upvotes: 2

Related Questions