0
我有一臺客戶端在同一臺機器上連接兩個不同的多播組(相同的端口號)。在客戶端,我使用epoll來監聽兩個套接字。 服務器嘗試向第一組發送組播消息。但是,epoll會在這兩個套接字上接收數據。是否因爲套接字在同一臺機器上並使用相同的端口?請指點使用epoll在客戶端監聽不同的多播套接字
代碼片段:
/* Client code to join multicast group */
multicastPort = "4321";
/* Resolve the multicast group address */
hints.ai_family = PF_UNSPEC;
hints.ai_flags = AI_NUMERICHOST;
if ((status = getaddrinfo(group_ip_address, NULL, &hints, &multicastAddr)) != 0)
{
perror("\nError g.");
}
hints.ai_family = multicastAddr->ai_family;
hints.ai_socktype = SOCK_DGRAM;
hints.ai_flags = AI_PASSIVE; /* Return an address we can bind to */
if (getaddrinfo(NULL, multicastPort, &hints, &localAddr) != 0)
perror("\nError f.");
/* Create socket for receiving datagrams */
if ((sd = socket(localAddr->ai_family, localAddr->ai_socktype, 0)) < 0)
perror("socket() failed");
/* lose the pesky "Address already in use" error message */
if (setsockopt(sd,SOL_SOCKET,SO_REUSEADDR,(char*)&yes,sizeof(int)) == -1)
perror("setsockopt");
/* Bind to the multicast port */
if (bind(sd, localAddr->ai_addr, localAddr->ai_addrlen) != 0)
perror("bind() failed");
struct ip_mreq multicastRequest; /* Multicast address join structure */
/* Specify the multicast group */
memcpy(&multicastRequest.imr_multiaddr,
&((struct sockaddr_in*)(multicastAddr->ai_addr))->sin_addr,
sizeof(multicastRequest.imr_multiaddr));
/* Accept multicast from any interface */
multicastRequest.imr_interface.s_addr = htonl(INADDR_ANY);
/* Join the multicast address */
if (setsockopt(sd, IPPROTO_IP, IP_ADD_MEMBERSHIP, (char*) &multicastRequest, sizeof(multicastRequest)) != 0)
perror("setsockopt() failed");
/* Create a datagram socket on which to receive. */
==================================================
/* client code to listen on epoll sockets*/
int fd_id= multicast_join(lo,group_ip);
//sprintf(display,"Listening to group %s ip address %s\n", grp_name, grp_ip_address);
sprintf(display,"Listening to group %s and ip %s\n", grp_name, grp_ip_address);
PRINT(display);
if(fd_id > 0){
ADD_CLIENT_IN_LL(client_info,grp_name,group_ip,fd_id);
event->data.fd = fd_id;
char buf[30];
sprintf(buf,"fd_id %d",fd_id);
PRINT(buf);
event->events = EPOLLIN|EPOLLET;
status = epoll_ctl(efd, EPOLL_CTL_ADD, fd_id, event);
if (status == -1)
{
perror("\nError while adding FD to epoll event.");
exit(0);
}
我認爲這是。您需要使用一個套接字和['IP_PKTINFO'](http://man7.org/linux/man-pages/man7/ip.7.html)選項來確定每個傳入數據報被髮送到哪個組。 – EJP