-1

I want to make a application in C on Linux where there are multiple processes running on one computer, which come from the same binary. It is not exactly defined how many of these processes there will be (2-20). I want them to find all the other running instances of the binary when they start up. The processes should communicate over UDP with Linux Sockets and when one application sends a packet every process should receive it.

At the moment i have set up some basic udp message sending between two clients with fixed predefined ports. The goal ist to have them start up and get some port assigned from the os. The applications then should find other instances of the same binary and communicate with them. How can implement this sort of searching ? At first i tried to make them all listen to some fixed port via SO_REUSEADDR, but then just the last process to start up will receive all traffic. Then i looked into Multi and Broadcasting, but i think i need different ips for that to work.

Thanks in advance

  • 1
    Hi there, Welcome to Stack Overflow! Please see [how to ask](https://stackoverflow.com/help/how-to-ask). We request you to show your effort first, what you have done and tried so far. We can not answer direct question where there are no efforts. Hope you understand. – rbashish Aug 13 '19 at 12:20
  • I guess this is what you want to do... https://stackoverflow.com/questions/16007311/multicasting-on-the-loopback-device – OlliWerPXC Aug 13 '19 at 12:22

1 Answers1

1

Each instance of your application should create a socket that is bound to the same port. You'll need to set the SO_REUSEADDR on the socket before binding to allow this to happen.

As you've already found, when you have multiple UDP sockets bound to the same port and a unicast packet arrives only one of those sockets will receive the packet. To get around that you'll have to use multicast. If the sockets are all listening on a multicast address and a multicast packet it sent, all sockets will receive the packet. This also has the advantage of working whether or not the processes are on the same host.

After you set SO_REUSEADDR and bind the socket, you'll want to join a multicast group by setting the IP_ADD_MEMBERSHIP option. You can use any valid multicast address for this in the 225.0.0.0 - 239.255.255.255 range (avoid 232.x.x.x as that is for source specific multicast) and all instances of the app should join the same group.

You should also set the IP_MULTICAST_IF option to set the network interface for outgoing multicast packets, and if you want the app to receive multicast messages that it sent itself, you'll also want to set IP_MULTICAST_LOOP.

dbush
  • 205,898
  • 23
  • 218
  • 273