Broccoli
Broccoli

Reputation: 81

recvfrom() socket programming Ubuntu

I posted a question yesterday and got some helpful feedbacks! So, I fixed a lot of my codes and now the problem I have is to extract data from recvfrom() and displaying them in printf(), here are my codes:

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);

Please help! Thank you..

Upvotes: 0

Views: 652

Answers (1)

David Ranieri
David Ranieri

Reputation: 41017

outMsgLen are the number of bytes received by recvfrom

If you want to display the text:

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

EDIT:

As @nos says there is an overflow risk if outMsg is not declared as char outMsg[MAX_MSG_LEN + 1];

A better choice would have been to use strlen(whatever) in recvfrom instead of MAX_MSG_LEN to determine the length.

Upvotes: 1

Related Questions