Reputation: 4398
I know there are a few similar question on SO, but I feel like everyone has a different issue that is causing this. So I'm posting my particular case.
I'm working on the raspberry pi, using raspbian, a debian derivative. I'm coding in ansi C. This is a server that sends some data to a udp client on another end through port 500.
#include <sys/socket.h>
#include <netinet/in.h>
#include <stdio.h>
int main()
{
int sockfd;
struct sockaddr_in servaddr,cliaddr;
socklen_t clilen;
char buffer[256];
sockfd=socket(AF_INET,SOCK_DGRAM,0);
bzero(&servaddr,sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_addr.s_addr=htonl(INADDR_ANY);
servaddr.sin_port=htons(500);
bind(sockfd,(struct sockaddr *)&servaddr,sizeof(servaddr));
sprintf(buffer,"hi this is a test \n");
if(sendto(sockfd,buffer,sizeof(buffer),0,(struct sockaddr *)&cliaddr,sizeof(cliaddr))==-1)
{ error("fail:")
};
return 0;
}
But this just gives me the error "invalid arguments", I can't figure out what could possibly be wrong. If the type of argument I supply to sendto is incorrect, this would fail on compile. But the type is correct and this compiles, only at runtime does it fail.
Upvotes: 0
Views: 3239
Reputation: 21425
You have no initialization for the cliaddr
structure. Thus, its contents are random. Your code compiles fine because you have a struct sockaddr_in
where it should be but the compiler cannot check if you have properly initialized it.
On the other hand, at runtime when sendto
is invoked the glibc
or the kernel finds out that that random data in the cliaddr
structure doesn't look like a valid address and throws up an invalid argument
error.
Solution: initialize the cliaddr
variable before using it.
Edit: You also need to properly initialize the socket, the third argument there shouldn't be 0
.
Second edit, read me: For resources I recommend the extraordinary guide of Beej. For your exact problem this subchapter can help.
Upvotes: 2