简体   繁体   中英

Multicast echo server

This is more of a conceptual confusion. I am making a multicast server which just echoes back the datagram received.Here's the code

    while (1) {
         cnt = recvfrom(sock, message, sizeof(message), 0, 
                (struct sockaddr *) &addr, &addrlen);
         //printf("%d \n",cnt);
         if (cnt < 0) {
            perror("recvfrom");
            exit(1);
         } else if (cnt == 0) {
            break;
         }
         printf("%s: message = \"%s\"\n", inet_ntoa(addr.sin_addr), message);
         addr.sin_addr.s_addr = inet_addr(EXAMPLE_GROUP);
         cnt = sendto(sock, message, sizeof(message), 0,
          (struct sockaddr *) &addr, addrlen);
         if (cnt < 0) {
            perror("sendto");
            exit(1);
         }

    }

The problem with this is as a multicast server will also receive the datagram. So, after it recieves a datagram, it sends, it again recieves the same datagram, and so on entering an infinite loop. Any pointers on how to implement such type of server?

您需要通过setsockopt().禁用多播环回setsockopt().

One option is what EJP said, to disable multicast loopback so that the sending machine doesn't receive a copy of its own multicast packet back. However, be aware that if you do that, you won't be able to test with clients and server all running on the same machine anymore, since IP_MULTICAST_LOOP is implemented at the IP routing level .

A second possible option to avoid infinite packet loops would be to have the echo-server send its response packets to a different multicast group than the one it listens on (or even have it send its responses via unicast rather than multicast; the server could call recvfrom() to find out the unicast source address of any packet it receives, so it's easy for it to know where to send the reply packet back to)

A third option would be to modify the contents of the packet somehow to mark it as already-seen, so that your server knows not to echo it a second time. For example, you could specify that your server will only echo packets whose first byte is set to zero, and when your server echoes a packet, it makes sure to set the packet's first byte to one before send()-ing it out. (Your clients would need to be aware of this convention, of course)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM