gpt4 book ai didi

C: 使用 sprintf( ) 做 IP 地址解析,不正确的值

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

我试图使用 sprintf() 来解析 IP 地址。 buf 存储从其他主机接收到的数据包。而buf中的测试数据为'\0xff'。我希望在 ip 中看到 255.255.255.255。但是我得到的是ip中的-1.-1.-1.-1

char buf[5];
char ip[18];
...
// They all have value 0xff, that is buf[0]=buf[1]=buf[2]=buf[3]='\0xff';
sprintf(ip, "'%d.%d.%d.%d'",buf[0],buf[1],buf[2],buf[3]);

似乎在 buf 中的每个字节都加一。我认为它应该与说明符有关,也许我应该为 unsigned int 使用说明符。然后我尝试了 %u%hhd。他们是不正确的。有人知道吗?是因为说明符吗?

最佳答案

这并没有真正回答这个问题,因为 GrahamS 已经很好地回答了这个问题,但是您可能想尝试使用为这种事情制作的 TCP/IP 堆栈的函数和结构:

#include <stdio.h>

#include <arpa/inet.h>
#include <netinet/in.h>

int main()
{
/*
* Using functions and structs that were made for this
*/

//this is really just a one-member struct with a uint_32t
struct in_addr addr;

//Convert Presenteation to Number (pton) for the AF_INET address family (IPv4)
inet_pton(AF_INET,"1.2.3.4",&addr);


//INET_ADDRSTRLEN -- how much space is needed to hold the presentation of an IP4 ip addresss?
//defined to 16 -- enough to hold 255.255.255.255 with the null terminator
char buf[INET_ADDRSTRLEN];

//convert back to string
inet_ntop(AF_INET,&addr, buf, sizeof(buf));

puts(buf);
return 0;
}

关于C: 使用 sprintf( ) 做 IP 地址解析,不正确的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31704927/

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