I am currently writing a small UDP server program in linux. The UDP server will receive packets from two different peers and will perform different operations based on from which peer it received the packet. I am trying to determine the source from where I receive the packet. However, when select
returns and recvfrom
is called, it returns with an error of Invalid Argument. If I pass NULL as the second last arguments, recvfrom succeeds.
I have tried declaring fromAddr as struct sockaddr_storage
, struct sockaddr_in
, struct sockaddr
without any success. Is their something wrong with this code? Is this the correct way to determine the source of the packet?
The code snippet follows.
`
/*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);
}
`
Return valueIf no error occurs, recvfrom returns the number of bytes received. If the connection has been gracefully closed, the return value is zero. Otherwise, a value of SOCKET_ERROR is returned, and a specific error code can be retrieved by calling WSAGetLastError.
For an UDP socket, recvfrom() reads the UDP data. So it returns 450 , provided you supply a buffer that is at least 450 bytes big. If you supply a buffer that is smaller than the received data, the data will be truncated, and recvfrom() will read as much data as can fit in the buffer you give it.
Unlike send(), the recv() function of Python's socket module can be used to receive data from both TCP and UDP sockets.
If no messages are available to be received and the peer has performed an orderly shutdown, recv() shall return 0. Otherwise, -1 shall be returned and errno set to indicate the error. Alternatively, you can also call perror() / strerror() to get a human-readable string related to the error.
You must initialise addrLen
to sizeof fromAddr
before calling recvfrom()
- it is an input/output parameter. Using struct sockaddr_storage
to declare fromAddr
is correct.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With