一个幼稚的实现(否inet_pton
)将使用 4 个数字并将它们打印到一个char
数组中
#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);
}
}
*编辑:一个受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);
}
}