问题描述
我知道,对于大多数人来说,这很简单,但是我正在尝试在一个循环中以+1递增一个ip地址。
示例:
$ p $
for(double ip = 1.1.1.1; ip {
printf( %f,ip);
$ b基本上我所要做的就是增加一个IP for循环。
我不知道什么类型的变量来存储IP,不知道如何增加它。
当我运行程序时,出现一个错误,说明这个数字有太多的小数点。
我也看到在互联网上,你必须存储IP的字符数组,但你不能增加一个字符数组(我知道)。
我应该存储哪个变量类型的IP /我该如何处理这个问题?感谢您。
解决方案天真的实现(no inet_pton
)会使用户4数字并将它们打印到 char
数组中
#include< stdio.h中>
$ b int int_inc(int * val){
if(* val == 255){
(* val)= 0;
返回1;
}
else {
(* val)++;
返回0;
int main(){
int ip [4] = {0};
char buf [16] = {0};
while(ip [3] 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);
$ b编辑:一个由alk创建的新实现
p>
struct ip_parts {
uint8_t vals [4];
};
union ip {
uint32_t val;
struct ip_parts部分;
};
int main(){
union ip ip = {0};
char buf [16] = {0};
while(ip.parts.vals [3] ip.val ++;
snprintf(buf,16,%d。%d。%d。%d,ip.parts.vals [3],ip.parts.vals [2],
ip.parts。瓦尔斯[1],ip.parts.vals [0]);
printf(%s \ n,buf);
}
}
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.
解决方案 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);
}
}
这篇关于如何增加一个循环中的IP地址? [C]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!