Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conversion of IP address to integer [duplicate]

Tags:

c

networking

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?

like image 961
mmuttam Avatar asked Apr 23 '12 15:04

mmuttam


1 Answers

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;
}
like image 183
OmnipotentEntity Avatar answered Sep 18 '22 18:09

OmnipotentEntity