Closed. This question is off-topic。它当前不接受答案。
                            
                        
                    
                
                            
                                
                
                        
                            
                        
                    
                        
                            想改善这个问题吗? Update the question,所以它是on-topic,用于堆栈溢出。
                        
                        6年前关闭。
                                                                                            
                
        
我知道这对大多数人来说非常简单,但是我试图在一个循环中将ip地址增加+1。

例:

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


基本上,我想做的就是在for循环中将ip值增加+1。
我不知道存储ip的变量类型,也不知道如何增加它。
每当我运行程序时,我都会收到一条错误消息,提示该数字有太多小数点。
我还在互联网上看到,您必须将IP存储在一个字符数组中,但是您不能增加一个字符数组(据我所知)。
我应该将ip存储在什么变量类型中/应该如何处理呢?谢谢。

最佳答案

一个简单的实现(没有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);
    }
}

07-24 09:46
查看更多