A naive implementation (no inet_pton
) would user 4 numbers and print them into a char
array
#include <stdio.h>
int inc_ip(int * val) {
if (*val == 255) {
(*val) = 0;
return 1;
}
else {
(*val)++;
return 0;
}
}
int main() {
int ip[4] = {0};
char buf[16] = {0};
while (ip[3] < 255) {
int place = 0;
while(place < 4 && inc_ip(&ip[place])) {
place++;
}
snprintf(buf, 16, "%d.%d.%d.%d", ip[3],ip[2],ip[1],ip[0]);
printf("%s\n", buf);
}
}
*Edit: A new implementation inspired by alk
struct ip_parts {
uint8_t vals[4];
};
union ip {
uint32_t val;
struct ip_parts parts;
};
int main() {
union ip ip = {0};
char buf[16] = {0};
while (ip.parts.vals[3] < 255) {
ip.val++;
snprintf(buf, 16, "%d.%d.%d.%d", ip.parts.vals[3],ip.parts.vals[2],
ip.parts.vals[1],ip.parts.vals[0]);
printf("%s\n", buf);
}
}
1
solved How to increment an IP address in a loop? [C] [closed]