gpt4 book ai didi

复制缓冲区中的 IP 地址

转载 作者:太空宇宙 更新时间:2023-11-04 06:51:40 26 4
gpt4 key购买 nike

我正在用 C 构建防火墙,但遇到以下问题。我在客户端请求一个 IP 地址,我得到 4 个数字(IP 地址的八位字节,采用点分四组格式)。就像这个例子:

255.255.197.0

我在 Integer 类型数据中得到这 4 个八位字节。为了将其复制到 Characters 缓冲区中,我使用了 sprintf() 函数,但出现了段错误。

char buffer[MAX_BUFF_SIZE];            // The buffer to save the IP address
bzero(buffer, sizeof(buffer)); // Clean the buffer

// Gets the address
int o1, o2, o3, o4;
do
{
printf("Introduce the 4 octets of the IP address (dotted quad format).\n");
printf("Numbers must go from 0 to 255.\n\n");

valid = TRUE;
printf("Introduce first octet (X.-.-.-): ");
scanf("%d", &o1);
printf("Introduce second octet (-.X.-.-): ");
scanf("%d", &o2);
printf("Introduce third octet (-.-.X.-): ");
scanf("%d", &o3);
printf("Introduce fourth octet (-.-.-.X): ");
scanf("%d", &o4);
if (o1 < 0 || o1 > 255 || o2 < 0 || o2 > 255 || o3 < 0 || o3 > 255 || o4 < 0 || o4 > 255)
{
printf("Error [Client]: Invalid number.\n");
valid = FALSE;
}
} while (valid == FALSE);

// When octets are valid
sprintf(buffer, "%d.%d.%d.%d", o1, o2, o3, o4); // Copy the address in String format in buffer
inet_aton(buffer, &my_rule.addr);
printf("The IP address is %s\n", my_rule.addr);

o1o2o3o4 是地址的 4 个八位字节。知道如何将这些整数放入 char 缓冲区吗?

最佳答案

这没有意义:

  printf("The IP address is %s\n", my_rule.addr);

s 转换说明符需要 0 终止 char 数组的第一个元素的地址,一个 C-“字符串” .

代码(很可能,因为您没有显示)传递一个 struct in_addr

编译器应该已经警告过你了。


顺便说一句,您知道 255.255.197.0 不是有效的 IP 地址,对吗?

关于复制缓冲区中的 IP 地址,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50275317/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com