Say I want to receive data from 239.1.2.3:20000 and also from 239.4.5.6:20001 in a linux C program. Can I do so with just one socket?
I can of course join multiple groups on the socket using the IP_ADD_MEMBERSHIP setsockopt
option, but, since the ports are different, I am not sure if it is possible to somehow "bind to both ports"
No, you can't bind a socket to 2 ports, you need a socket per port.
In TCP, there needs to be one socket per client. This is because the socket needs to have a connection "accepted." This is done by calling accept on the server's listening socket, and it returns a new socket (with a new port) that denotes that specific client-server connection.
In UDP, there is no "connection," but rather, you just send data to a socket and hope it gets there (it might not). If you use a UDP socket, all your clients can send data to it, and your server won't have to call accept on incoming connections. You will have to create your own protocol to identify the clients sending the messages (inside hte message that is, you'll have to parse it to see if its client 1 or client2).
Let me know if this is unclear.
来源:https://stackoverflow.com/questions/17837492/receiving-multicast-data-from-different-groups-on-the-same-socket-in-linux