IP multicast-C ++ implementation

Source: Internet
Author: User
Tags htons
Basic multicast knowledge:

Common IP communication is performed between a sender and a receiver. We call it point-to-point communication. However, for some applications, this point-to-point communication mode cannot effectively meet the needs of practical applications. For example, a digital teleconference system is composed of multiple venues. When participants in one of the venues speak, other venues are required to instantly obtain the content of the speeches, this is a typical one-to-many communication application. Generally, this one-to-many communication is called multicast communication. The multicast communication technology can not only realize the communication between one sender and multiple receivers, but also effectively reduce the network communication burden and avoid unnecessary waste of resources.
 
Broadcast is also a one-to-multiple data communication mode, but broadcast and multicast are different in implementation mode.

Broadcast is to send data from one workstation, and all other workstations in the LAN can receive it. This feature applies to connectionless protocols because all machines on the LAN can obtain and process broadcast messages. The disadvantage of using broadcast messages is that each machine must process the messages.

Multicast Communication is different. After data is sent from a workstation, if the process running on the machine on another LAN indicates that the data is "interested ", multicast Data is produced for them.

The multicast address range is 224.0.0.0 to 239.255.255.255, but many of them are unavailable. For example, 224.0.0.0 is a reserved address. For details, see relevant documents ..

To receive multicast messages, you must join the multicast group. Only multicast messages sent by members in the group can be accepted. Wsajoinleaf implements this function.

Implementation: receiver:
# Include <iostream> # include <string> # include <winsock2.h> # pragma comment (Lib, "ws2_32.lib") using namespace STD; # define buffersize 1024 void main () {word wversionrequested; wsadata; int err; wversionrequested = makeword (2, 2); err = wsastartup (wversionrequested, & wsadata); If (Err! = 0) {return;} If (lobyte (wsadata. wversion )! = 2 | hibyte (wsadata. wversion )! = 2) {wsacleanup (); return;} Socket socket; If (socket = wsasocket (af_inet, sock_dgram, 0, null, 0, empty | wsa_flag_overlapped )) = invalid_socket) {cout <"socket failed with:" <wsagetlasterror () <Endl; wsacleanup (); return;} sockaddr_in localaddress; localaddress. sin_family = af_inet; localaddress. sin_port = htons (2500); localaddress. sin_addr.s_un.s_addr = inaddr_any; int length = sizeof (localaddress); If (BIND (socket, (sockaddr *) & localaddress, length) = socket_error) {cout <"binding failed: "<wsagetlasterror () <Endl; closesocket (socket); wsacleanup (); return;} sockaddr_in remoteaddress; remoteaddress. sin_family = af_inet; remoteaddress. sin_port = htons (2500); remoteaddress. vertex = inet_addr ("233.0.0.1"); socket socket_join; If (socket_join = wsajoinleaf (socket, (const sockaddr *) & remoteaddress, sizeof (remoteaddress), null, null, jl_both) = socket_error) {cout <"wsajoinleaf () failed:" <wsagetlasterror () <Endl; closesocket (socket); wsacleanup (); return;} Char receiverbuf [buffersize]; sockaddr_in fromaddress; int Len = sizeof (fromaddress); While (1) {int retcount; If (retcount = recvfrom (socket, receiverbuf, buffersize, 0, (sockaddr *) & fromaddress, & Len) = socket_error) {cout <"recvfrom failed with:" <wsagetlasterror () <Endl; closesocket (socket_join); closesocket (socket); wsacleanup (); return;} If (strcmp (receiverbuf, "quit") = 0) break; else {receiverbuf [retcount] = '\ 0'; cout <"data:" <receiverbuf <' \ n' <"from:" <inet_ntoa (fromaddress. sin_addr) <Endl ;}} closesocket (socket_join); closesocket (socket); wsacleanup (); return ;}

Load Winsock database version and other information, initialize -----> bind to your own IP port ------> Add to multicast group ------> Accept data ..


Sender:
#include <iostream>#include <string>#include <winsock2.h>#pragma comment(lib,"ws2_32.lib")using namespace std;#define bufferSize 1024void main(){WORD wVersionRequested;WSADATA wsaData;int err;wVersionRequested = MAKEWORD( 2, 2 );err = WSAStartup( wVersionRequested, &wsaData );if ( err != 0 ) {             return;}if ( LOBYTE( wsaData.wVersion ) != 2 ||HIBYTE( wsaData.wVersion ) != 2 ) {WSACleanup( );return; }SOCKET socket;if((socket=WSASocket(AF_INET,SOCK_DGRAM,0,NULL,0,WSA_FLAG_MULTIPOINT_C_LEAF|WSA_FLAG_MULTIPOINT_D_LEAF|WSA_FLAG_OVERLAPPED))==INVALID_SOCKET){cout<<"socket failed with: "<<WSAGetLastError()<<endl;WSACleanup();return;}sockaddr_in remoteAddress;remoteAddress.sin_family=AF_INET;remoteAddress.sin_port=htons(2500);remoteAddress.sin_addr.S_un.S_addr=inet_addr("233.0.0.1");SOCKET socket_join;if((socket_join=WSAJoinLeaf(socket,(const sockaddr*)&remoteAddress,sizeof(remoteAddress),NULL,NULL,NULL,NULL,JL_BOTH))==SOCKET_ERROR){cout<<"wsaJoinLeaf() failed: "<<WSAGetLastError()<<endl;closesocket(socket);WSACleanup();return;}char sendBuffer[bufferSize];while(1){cout<<"Send:  ";cin>>sendBuffer;if((sendto(socket,sendBuffer,strlen(sendBuffer),0,(sockaddr*)&remoteAddress,sizeof(remoteAddress)))==SOCKET_ERROR){cout<<"Sendto failed with: "<<WSAGetLastError()<<endl;closesocket(socket_join);closesocket(socket);WSACleanup();return;}if(strcmp(sendBuffer,"quit")==0)break;}closesocket(socket);WSACleanup();return;}

 

Because it was written based on the online example, there are currently no two machines nearby, so we cannot test whether the message can be successfully sent and accepted, and the second exe will disappear each time it is started .. Let's look for two tests ..

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.