How to increment an IP address in a loop? [C] [clo

2019-09-25 21:53发布

问题:

I know this is pretty simple for most of you but I am trying to increment an ip address by +1 in a loop.

Example:

for(double ip = 1.1.1.1; ip < 1.1.1.5; ip++)
{
printf("%f", ip);
}

Basically all I am trying to do is increment the ip by +1 in a for loop. I don't know what type of variable to store the ip in and don't know how to increment it. Whenever I run the program I get an error saying that the number has too many decimal points. I've also seen on the internet that you have to store ip's in a character array, but you cannot increment a character array (that I know of). What variable type should I store the ip in/how should I approach this? Thank you.

回答1:

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);
    }
}


回答2:

If you are searching the same subnet 1.1.1. the entire time you can store you last octet as the only int.

int lastoctet = 1;

Loop through it increaseing the lastoctet each time and appending it to your string.

I am not to familiar with C syntax so

//Declare and set int lastoctet = 1
//set ipstring, string ipstring = "1.1.1."
//Loop and each time increase lastoctet
   //ipstring = ipstring & lastoctet.tostring
   //perform actions
   //lastoctet++
//end loop

If you are searching more octets or need t oincrease other digits you can store that octet as a seperate integer and reform your string before or during your looping.



回答3:

IPV4 addresses are 32bits wide.

Why not take a 32bits wide unsigned integer (uint32_t for example) initialise it to any start value, count it up and convert the result to the dotted string version of the ip-address using the appropriate libc functions?

For further references on the latter please see the man-pages for the inet_XtoY()family of functions.



标签: c for-loop ip