I would like to print all the possible IPs for a given mask. I have this code to get it but it seems I'm missing something since I can't get the list of IPs. I've based my code in this other post.
unsigned int ipaddress, subnetmask;
inet_pton(AF_INET, b->IpAddressList.IpAddress.String, &ipaddress);
inet_pton(AF_INET, b->IpAddressList.IpMask.String, &subnetmask);
for (unsigned int i = 1; i<(~subnetmask); i++) {
auto ip = ipaddress & (subnetmask + i);
}
Example: ipaddress= 172.22.0.65 netmask= 255.255.252.0
I expect:
172.22.0.1 172.22.0.2 172.22.0.3 172.22.0.4 ...
Update: I tried this code, but it does not work, either:
char* ip = "172.22.0.65";
char* netmask = "255.255.252.0";
struct in_addr ipaddress, subnetmask;
inet_pton(AF_INET, ip, &ipaddress);
inet_pton(AF_INET, netmask, &subnetmask);
unsigned long first_ip = ntohl(ipaddress.s_addr & subnetmask.s_addr);
unsigned long last_ip = ntohl(ipaddress.s_addr | ~(subnetmask.s_addr));
for (unsigned long ip = first_ip; ip <= last_ip; ++ip) {
unsigned long theip = htonl(ip);
struct in_addr x = { theip };
printf("%s\n", inet_ntoa(x));
}
You can bitwise AND
the input IP address with the input mask to determine the first IP in the range, and bitwise OR
the input IP address with the inverse of the mask to determine the last IP in the range. Then you can loop through the values in between.
Also, inet_pton(AF_INET)
expects a pointer to a struct in_addr
, not an unsigned int
.
Try this instead:
struct in_addr ipaddress, subnetmask;
inet_pton(AF_INET, b->IpAddressList.IpAddress.String, &ipaddress);
inet_pton(AF_INET, b->IpAddressList.IpMask.String, &subnetmask);
unsigned long first_ip = ntohl(ipaddress.s_addr & subnetmask.s_addr);
unsigned long last_ip = ntohl(ipaddress.s_addr | ~(subnetmask.s_addr));
for (unsigned long ip = first_ip; ip <= last_ip; ++ip) {
unsigned long theip = htonl(ip);
// use theip as needed...
}
For instance:
172.22.0.65 & 255.255.252.0 = 172.22.0.0
172.22.0.65 | 0.0.3.255 = 172.22.3.255