UDP server recvfrom() always returns -1? :(

Posted on 16th Feb 2014 by admin

Hello all,
I am getting a very strange error in my code :( I am writing a server application in C, to send and receive UDP packets to/from a client. Right now, im just running a loop in which the server receives packets using recvfrom() however.... the function seems to block and everytime I send it something, it sets errno to "resource temporarily unavailable" which is strange, cause it blocks until I send something, meaning that it knows something came no? However, recvfrom always returns -1 This is how I initialized the socket:

//struct timeval tv;

if((s = socket(AF_INET, SOCK_DGRAM, 0))==-1)
return 0;

bzero(&si_me,sizeof(si_me));
si_me.sin_family = AF_INET;
si_me.sin_port = htons(PORT);
si_me.sin_addr.s_addr = htonl(INADDR_ANY);

/*** Set socket timeout ***
tv.tv_sec = 1;
tv.tv_usec = 0;
if (setsockopt(s, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv)) < 0)
{
printf("Couldn't set socket timeoutn");
return 0;
}*/

if(bind(s,(struct sockaddr*) &si_me, sizeof(si_me))==-1)
return 0;

return 1;

and then I ran:
do
{
done = recvData();
printf("Received %d n", done);

}while(done == 0);

with recvData() being:

int recvData(void)
{
if (recvfrom(s, (char*)&buf, UDP_BUFFER_LEN, 0, (struct sockaddr*) &si_other_comp, &slen)==-1)
{
printf("Couldn't read socket (%s)n",strerror(errno));
return 0;
}

return 1;
}

so, program does nothing until it gets a packet, then says it cant read it and then continues doing nothing until it gets another packet.... any ideas?

Other forums