0

我昨天发布了一个问题,并得到了一些有用的反馈!所以,我修复了很多我的代码,现在我遇到的问题是从中提取数据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);

请帮忙!谢谢..

4

1 回答 1

1

outMsgLen是接收到的字节数recvfrom

如果要显示文本:

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

编辑:

正如@nos 所说,如果outMsg未声明为,则存在溢出风险char outMsg[MAX_MSG_LEN + 1];

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

于 2013-05-27T13:04:14.547 回答