recvfrom()套接字编程Ubuntu

时间:2013-05-27 12:50:20

标签: c linux sockets ubuntu

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

请帮忙!谢谢..

1 个答案:

答案 0 :(得分:1)

outMsgLenrecvfrom

收到的字节数

如果要显示文字:

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

修改

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

,则存在溢出风险

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