Receiving multicast data from different groups on the same socket in linux

蓝咒 提交于 2019-12-07 08:50:52

问题


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"


回答1:


No, you can't bind a socket to 2 ports, you need a socket per port.




回答2:


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!