实现组播接收
#define MULTICAST_ADDR "239.2.1.22"
#define UDP_RCV_PORT 1234
typedef struct{
int fd;
struct sockaddr_in sockServer;
struct sockaddr_in sockClient;
uint8_t rcvData[1024];
int rcvLen;
}SocketInfo_ts;
SocketInfo_ts udpClient;
//create a udp socket
int iCreatUdpClient(SocketInfo_ts* udpSock)
{
struct ip_mreq group;
if((udpSock->fd=socket(AF_INET,SOCK_DGRAM,0))<0)
{
return 0;
}
udpSock->sockClient.sin_family=AF_INET;
udpSock->sockClient.sin_port=htons(UDP_RCV_PORT);
udpSock->sockClient.sin_addr.s_addr=htonl(INADDR_ANY);
if(bind(udpSock->fd,(struct sockaddr*)&udpSock->sockClient,sizeof(struct sockaddr_in))<0)
{
return 0;
}
group.imr_interface.s_addr=htons(INADDR_ANY);
group.imr_multiaddr.s_addr=inet_addr(MULTICAST_ADDR);
setsockopt(udpSock->fd,IPPROTO_IP,IP_ADD_MEMBERSHIP,(char *)&group,sizeof(group));
return 1;
}
void vUdpThread(void* argument)
{
uint32_t fromSize;
fd_set fdSockSet;
struct timeval timeout;
//init udpClient
iCreatUdpClient(&udpClient);
for(;;)
{
FD_ZERO(&fdSockSet);
FD_SET(udpClient.fd,&fdSockSet);
timeout.tv_sec=1;
timeout.tv_usec=0;
if(select(udpClient.fd+1,&fdSockSet,NULL,NULL,&timeout)>0)
{
if(FD_ISSET(udpClient.fd,&fdSockSet))
{
fromSize=sizeof(struct sockaddr_in);
udpClient.rcvLen=recvfrom(udpClient.fd,udpClient.rcvData,1024,0,(struct sockaddr*)&udpClient.sockServer,&fromSize);
}
}
}
}
/*-----------------------------------------------------------------------------------*/
void vUdpInit(void)
{
sys_thread_new("udp_thread", vUdpThread, NULL, DEFAULT_THREAD_STACKSIZE,UDP_THREAD_PRIO );
}
|