Possible Duplicate:
IP Address to Integer – C
How do I convert an IP address to integer which has the following form:
A.B.. or A.B.C.* or A...* or ...
I want to write a C program which can determine if an IP address is a subset of another. e.g the IP address 192.168.125.5 is a subset of 192.168... Now I want to convert both the IP addresses to unique integers and subsequently check if one is a subset of the other. Is there a way to achieve this?
An IP address, e.g. 192.168.0.1 can be written as an integer easily by writing it in hex which becomes 0xC0 0xA8 0x00 0x01 or just 0xC0A80001
Then it’s just a case of bit matching, so you construct a corresponding subnet mask, 255.255.0.0 which is just 0xFFFF0000 and you can test that both match by doing:
where one side of the equality test is the “base stuff you care about” and the other side is a real address, with a given mask being the same on both sides.
In general you can construct a suitable mask by setting things which are ‘*’ to be 0 and things which are actual numbers to be 0xFF, if you want finer grain masks it’s hard to express with ‘*’.