How to increment an IP address in a loop? [C] -
i know pretty simple of trying increment ip address +1 in loop.
example:
for(double ip = 1.1.1.1; ip < 1.1.1.5; ip++) { printf("%f", ip); }
basically trying increment ip +1 in loop. don't know type of variable store ip in , don't know how increment it. whenever run program error saying number has many decimal points. i've seen on internet have store ip's in character array, cannot increment character array (that know of). variable type should store ip in/how should approach this? thank you.
a naive implementation (no inet_pton
) user 4 numbers , print them 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: new implementation inspired 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); } }
Comments
Post a Comment