gpt4 book ai didi

c - recvfrom() 套接字编程 Ubuntu

转载 作者:太空宇宙 更新时间:2023-11-04 11:23:00 25 4
gpt4 key购买 nike

我昨天发布了一个问题并得到了一些有用的反馈!所以,我修复了很多代码,现在我遇到的问题是从 recvfrom() 中提取数据并将它们显示在 printf() 中,这是我的代码:

clientAddr.sin_family = AF_INET;
clientAddr.sin_addr.s_addr = htonl(INADDR_ANY);
userIP.s_addr = RespMessage.user[i].ipAddr;
clientAddr.sin_addr.s_addr = userIP.s_addr;

printf("Username FOUND! What do you want to say? \n");
fgets(inMsg, MAX_MSG_LEN, stdin);
chatMsg = (UDPchat_t *)inMsg;

send = sendto(UDP_socketID, chatMsg->message, sizeof(chatMsg->message), 0, (struct sockaddr*)&clientAddr, size_c);
if (send < 0)
{
printf("Sending failure : %d", errno);
continue;
}
else
{
printf("Message sent!\n");
continue;
}

outMsgLen = recvfrom(UDP_socketID, outMsg, MAX_MSG_LEN, 0, (struct sockaddr *)&clientAddr, (socklen_t*)&size_c);
send = gettimeofday(&timeVal, NULL);
curtime = timeVal.tv_sec;
printf("[%ld] Rcvd pkt from: ", outMsgLen);

求助!谢谢..

最佳答案

outMsgLenrecvfrom

接收到的字节数

如果要显示文字:

outMsg[outMsgLen] = '\0';
printf("%s\n", outMsg);

编辑:

正如@nos 所说,如果 outMsg 未声明为 char outMsg[MAX_MSG_LEN + 1];

,则存在溢出风险

更好的选择是在 recvfrom 中使用 strlen(whatever) 而不是 MAX_MSG_LEN 来确定长度。

关于c - recvfrom() 套接字编程 Ubuntu,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16773602/

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