Help with non blocking udp socket
Hi All,
Below is my code for a non blocking UDP socket, this code compiles fine with g++, however when I run it i get the error NON: recvfrom: Resource temporarily unavailable. Please help with any advice
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <time.h>
#include <string>
#include <stdio.h>
#include <iostream>
#include <map>
#include <unistd.h>
#include <fcntl.h>
using namespace std;
int main(int argc, char *argv[])
{
struct sockaddr_in addr;
int sock, nbytes,addrlen, flags;
struct ip_mreq mreq;
char msgbuf[1024];
int yes = 1;
if ((sock = socket(AF_INET, SOCK_DGRAM, 0)) == -1)
{
perror("socket");
exit(1);
}
flags = fcntl(sock,F_GETFL);
flags |= O_NONBLOCK;
// allow multiple sockets to use the same PORT number
if ( (setsockopt (sock, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof( yes )) < 0))
{
perror("Reusing ADDR failed");
exit(1);
}
// setting up destination addres
memset(&addr, 0, sizeof( addr ));
addr.sin_family=AF_INET;
addr.sin_addr.s_addr=inet_addr(SOCK_GROUP);
addr.sin_port=htons(SOCK_PORT);
// bind to receive address
if (bind (sock, (struct sockaddr *) &addr, sizeof( addr )) < 0)
{
perror("bind");
exit(1);
}
//Join the multicast group
mreq.imr_multiaddr.s_addr=inet_addr(SOCK_GROUP);
mreq.imr_interface.s_addr=htonl(INADDR_ANY);
if (setsockopt (sock, IPPROTO_IP, IP_ADD_MEMBERSHIP, &mreq, sizeof( mreq )) < 0)
{
perror("setsockopt");
exit(1);
}
fcntl(sock, F_SETFL, flags);
// now just enter a read-print loop
while(1) {
addrlen=sizeof(addr);
if ((nbytes = recvfrom(sock, msgbuf, sizeof( msgbuf ), 0, (struct sockaddr *) &addr, (socklen_t*) &addrlen)) < 0)
{
perror("NON: recvfrom");
exit(1);
}//Closes the if
else
{
cout <<" got something "<<endl;
}
}
};
|