Recvfrom returns an invalid argument when passing * from *

I am currently writing a small UDP server program on Linux. The UDP server will receive packets from two different peers and will perform different operations based on which it received the packet. I am trying to determine the source where I get the package from. However, when select returns and recvfrom is called, it returns with an invalid argument error. If I pass NULL as the last second arguments, recvfrom will succeed.

I tried to declare fromAddr as struct sockaddr_storage , struct sockaddr_in , struct sockaddr without any success. Is there something wrong with this code? Is it correct to determine the source of the package?

Below is a snippet of code.

 ` /*TODO : update for TCP. use recv */ if((pkInfo->rcvLen=recvfrom(psInfo->sockFd, pkInfo->buffer, MAX_PKTSZ, 0, /* (struct sockaddr*)&fromAddr,*/ NULL, &(addrLen) )) < 0) { perror("RecvFrom failed\n"); } else { /*Apply Filter */ #if 0 struct sockaddr_in* tmpAddr; tmpAddr = (struct sockaddr_in* )&fromAddr; printf("Received Msg From %s\n",inet_ntoa(tmpAddr->sin_addr)); #endif printf("Packet Received of len = %d\n",pkInfo->rcvLen); } ` 
+6
linux sockets
source share
2 answers

You must initialize addrLen to sizeof fromAddr before calling recvfrom() - this is an I / O parameter. Using struct sockaddr_storage to declare fromAddr correct.

+17
source share

I had the same problem:

 Invalid arguments 'Candidates are: int recvfrom(int, void *, unsigned int, int, sockaddr *, unsigned int *) ' 

in the same code:

 recvfrom(sockFd, buffer, MAX_PKTSZ, 0, (struct sockaddr*)&fromAddr, &addrLen) 

My mistake was that I used the regular int type unsigned int for addrLen :

 unsigned int addrLen; addrLen = sizeof(fromAddr); 
0
source share

All Articles