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?
What you want is to determine if an IP address is in a subnet, and to do that you want to apply a netmask. There are probably (certainly) libraries already out there to do what you want. This is if you want to roll your own.
If this IP address comes from a trusted source (ie, not a user), then you can simply extract the IP address from a standard C-string by doing something like:
char ipAddressString[16] = "192.168.125.5"
char netMaskString[16] = "255.255.0.0"
char subnetString[16] = "192.168.0.0"
uint32_t ipAddress = parseIPV4string(ipAddressString);
uint32_t netmask = parseIPV4string(netmaskString);
uint32_t subnet = parseIPV4string(subnetString);
if (ipAddress & netmask == subnet) {
return true;
}
uint32_t parseIPV4string(char* ipAddress) {
char ipbytes[4];
sscanf(ipAddress, "%uhh.%uhh.%uhh.%uhh", &ipbytes[3], &ipbytes[2], &ipbytes[1], &ipbytes[0]);
return ipbytes[0] | ipbytes[1] << 8 | ipbytes[2] << 16 | ipbytes[3] << 24;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With