Visual C + + implements LAN IP multicast

Source: Internet
Author: User
Tags strcmp htons

In a local area network, administrators often need to send a piece of information to a group of users. If you use a one-to send method, although it is feasible, but too cumbersome, there will often be missed, wrong hair. In order to solve this group communication problem more effectively, a kind of multicast technology (also commonly called multicast communication) is presented, which is based on the IP layer communication technology. To help the reader understand, the concept of multicasting is briefly described below.

As we all know, ordinary IP communication is between a sender and a receiver, we often call it peer-to-peer communication, but for some applications, this point-to-point communication mode can not effectively meet the needs of practical applications. For example, a digital teleconferencing system consists of several venues, when the participants in one of the venues speak, requesting that other venues can immediately get the content of this statement, which is a typical one-to-many communication applications, often referred to this pair of multiple communication is called multicast communication. The use of multicast communication technology can not only realize the function of communication between a sender and multiple receivers, but also can effectively reduce the burden of network communication and avoid the unnecessary waste of resources.

Broadcast is also a mode of implementing a one-to-many data communication, but the broadcast and multicast are different in implementation mode. Broadcasting is the sending of data from a workstation, and all other workstations within the LAN can receive it. This feature applies to a no-connection protocol because all machines on the LAN can acquire and process broadcast messages. The disadvantage of using broadcast messages is that each machine must process the message. Multicast traffic is different, and when the data is sent from a workstation, the multicast data is made to the process that runs on the other LAN if it is "interested" in the data.

This example consists of sender and receiver two programs, sender user input Multicast data from the console, receiver side all require to join the same multicast group, to complete receiving sender sent multicast data.

I. Implementation method 1, protocol support

Not all protocols support multicast traffic, and for the Win32 platform, only two protocols (IP/ATM) that can be accessed from within Winsock provide support for multicast traffic. Because the communication application is usually based on the TCP/IP protocol, this article discusses the multicast communication technology only for the IP protocol.

Platforms that support multicast communication include Windows CE 2.1, Windows 95, Windows 98, Windows NT 4, Windows 2000, and windowsxp. Since version 2.1, Windows CE has started to implement support for IP multicasting. This article is based on the WindowsXP Professional Edition platform.

2. Multicast address

IP uses a class-D address to support multicasting. Each class D address represents a group of hosts. A total of 28 bits are available to identify the group. So there can be up to 2.5 billion groups at the same time. When a process sends a grouping to a class D address, it will do its best to send it to all members of the group, but not all of them. Some members may not receive this grouping. For example, assuming that five nodes want to communicate with each other through I-P multicasting, they can join the same group address. When all is added, any data sent by one node is copied exactly one copy, sent to each member within the group, even to the node that originated the data. Class D I p address range between 244.0.0.0 to 239.255.255.255. It is divided into two categories: permanent address and temporary address. Permanent addresses are reserved for special purposes. For example, 244.0.0.0 is not used at all (nor can it be used), 244.0.0.1 represents all systems (hosts) within the subnet, and 244.0.0.2 represents all routers within the subnet. In the RFC 1700 file, a detailed list of all reserved addresses is provided. This file is a list of all the resources reserved for a special purpose and can be found as a reference. The Internet Assigned digital Experts Group (I a N a) is responsible for the maintenance of this list. In table 1, we summarize some of the addresses currently labeled "Reserved". Temporary group addresses must be created before they are used, and a process can require its host to join a specific group, and it can also require its host to be detached from the group. When the last process on the host is detached from a group, the group address is no longer present in this host. Each host is to record which group its processes currently belong to. Table 1 part of the permanent address description:

Address description
244.0.0.1 Base Address (reserved)
244.0.0.1 all systems on the subnet
All routers on the 244.0.0.2 subnet
244.0.0.5 all OSPF routers on the subnet
244.0.0.6 all specified OSPF routers on the subnet
244.0.0.9RIP 2nd version Group address
244.0.1.1 Network Time Protocol
244.0.1.24WINS Server Group Address

3. Multicast routers

Multicast is implemented by a special multicast router, which can also be a common router. Each multicast router sends a hardware multicast message per minute to the hosts on the subnet (the destination address is 244.0.0.1), requiring them to report which group their processes currently belong to, and each host to return the class D addresses it is interested in. These queries and responses are grouped using IGMP (Internet Group Management Protocol), which is roughly similar to ICMP. It has only two groupings: Query and response, all with a simple fixed format, where the first field of the payload field is some control information, the second field is a Class D address, which is described in detail in RFC1112.

The choice of multicast routers is implemented through spanning trees, where each multicast router uses the modified distance vector protocol and its neighbors to exchange information so that each router is constructed with a spanning tree that overrides all the crew members. Many optimization methods are used when pruning spanning tree and removing unrelated routers and networks.

4. Library Support

Winsock provides API function calls that implement multicast traffic. For IP multicasting, Winsock provides two different implementations, depending on which version of Winsock is being used. The first method is provided by WINSOCK1, which requires a socket option to join a group, and the other is provided by WinSock2, which is to introduce a new function that is specifically responsible for the addition of the multicast group, which is wsajoinleaf, which is irrelevant to the basic level protocol. This article will Apple told the main steps of multicast implementation through the implementation process of a multicast communication instance. Because Window98 later versions are installed with more than Winsock2.0 versions, this example is developed on the WinSock2.0 platform, but in which the WINSOCK1 implementation differs.

Second, the programming step

1. Start visual c++6.0 and create a console project Project Multicase. Add sender and receiver two items to this project. Receiver Project Implementation steps:

(1), create a sock_dgram type of socket.
(2), bind this socket to a local port in order to receive multicast data sent by the server side.
(3), join the multicast group.

A wsajoinleaf is introduced in ①, WinSock2, and this function is prototyped as follows:

Const struct int Namelen, Lpwsabuf lpcallerdata, Lpwsabuf lpcalleedata, Lpqos lpsqos,lpqos Lpgqos, DWORD dwFlags);

Where the first parameter s represents a socket handle, which is returned from WSASocket. The socket passed in must be created with the appropriate multicast flag, otherwise wsajoinleaf will fail and return error wsaeinval. The second parameter is the SOCKADDR (socket address) structure, which is determined by the protocol currently in use, and for the IP protocol, this address specifies the multicast group to which the host intends to join. The third parameter, Namelen (name length), is used to specify the length of the name parameter, in bytes. The function of the fourth parameter, Lpcallerdata (caller data), is to transfer a data buffer to the other party that communicates with itself after the session is established. The fifth parameter, Lpcalleedata (called Caller data), is used to initialize a buffer and receive data from each other after the session has been built. Note on the current Windows platform, both the Lpcallerdata and Lpcalleedata parameters are not actually implemented and should be set to null. The Lpsqos and Lpgqos parameters are settings for QoS (quality of service) and are usually also set to NULL, see MSDN or related Books for QoS content. The last parameter, dwflags, indicates that the host is sending data, receiving data, or acquiring or receiving a merger. The optional values for this parameter are: Jl_sender_only, jl_receiver_only, or Jl_both.

②, adding a multicast group to the WINSOCK1 platform requires calling the SetSockOpt function and setting the Ip_add_membership option to specify the address structure of the group to which you want to join. The implementation code is listed in the following code comment.

#p #

(4), receive multicast data.

Sender implementation steps:

(1), create a sock_dgram type of socket.
(2), join the multicast group.
(3), send multicast data.

3, compile two projects, the following steps in the local area network test:

(1), copy the Sender.exe to the PC that sends the multicast data.
(2), copy the Receiver.exe to multiple PCs that require receiving multicast data.
(3), the respective operation of the corresponding procedures.
(4), after entering the multicast data on the sender PC, you can see the input multicast data on receiver PC.

Third, the program code

RECEIVER.C Program code
#include <winsock2.h>#include<ws2tcpip.h>#include<stdio.h>#include<stdlib.h>#defineMcastaddr "233.0.0.1"//This example uses the multicast group address. #defineMcastport 5150//the local port number of the binding. #defineBUFSIZE 1024//receives the data buffer size. intMainintargcChar**argv) {Wsadata WSD;structSockaddr_in Local,remote, from; SOCKET sock,sockm; TCHAR Recvbuf[bufsize]; /*struct ip_mreq mcast;//Winsock1.0*/   intLen =sizeof(structsockaddr_in); intret;//Initialize WinSock2.2   if(WSAStartup (Makeword (2,2), &AMP;WSD)! =0) {printf ("WSAStartup () failed\n"); return-1;} /*Create a SOCK_DGRAM type of socket where wsa_flag_multipoint_c_leaf indicates that IP multicasting belongs to the "no root" type on the control surface layer; Wsa_flag_multipoint_d_leaf indicates that IP multicasting is "no root" on the data plane, see the MSDN note for concepts related to controlling the surface layer and the data plane. */   if(Sock=wsasocket (Af_inet,sock_dgram,0Null0, Wsa_flag_multipoint_c_leaf| Wsa_flag_multipoint_d_leaf|wsa_flag_overlapped)) ==invalid_socket) {printf ("Socket failed with:%d\n", WSAGetLastError ());  WSACleanup (); return-1;} //bind sock to a port on this machine. local.sin_family =af_inet; Local.sin_port=htons (mcastport); Local.sin_addr.s_addr=Inaddr_any;if(Bind (sock, (structsockaddr*) &local,sizeof(local)) ==socket_error) {printf ("bind failed with:%d \ n", WSAGetLastError ());  Closesocket (sock);  WSACleanup (); return-1;} //join a multicast groupremote.sin_family =af_inet; Remote.sin_port=htons (mcastport); Remote.sin_addr.s_addr=inet_addr (mcastaddr);/*Winsock1.0*/   /*mcast.imr_multiaddr.s_addr = inet_addr (mcastaddr); mcast.imr_interface.s_addr = Inaddr_any; if (setsockopt (SOCKM, Ipproto_ip,ip_add_membership, (char*) &mcast,sizeof (mcast)) = = Socket_error) {printf ("setsockopt (ip_add_  Membership) failed:%d\n ", WSAGetLastError ());  Closesocket (SOCKM);  WSACleanup (); return-1; }*/   /*Winsock2.0*/   if(sockm = Wsajoinleaf (sock, (sockaddr*) &remote,sizeof(remote), Null,null,null,null,jl_both)) ==invalid_socket) {printf ("wsajoinleaf () failed:%d\n", WSAGetLastError ());  Closesocket (sock);  WSACleanup (); return-1;} //receives multicast data and exits when the received data is "quit".     while(1) {if(ret = Recvfrom (sock,recvbuf,bufsize,0,(structsockaddr*) & from, &len)) = =socket_error) {printf ("Recvfrom failed with:%d\n", WSAGetLastError ());   Closesocket (SOCKM);   Closesocket (sock);   WSACleanup (); return-1; }if(strcmp (Recvbuf,"QUIT") ==0) Break; Else{Recvbuf[ret]=' /'; printf ("RECV: '%s ' from <%s> \ n", Recvbuf,inet_ntoa ( from. sin_addr)); }} closesocket (SOCKM); Closesocket (sock); WSACleanup (); return 0;}
SENDER.C Program code
#include <winsock2.h>#include<ws2tcpip.h>#include<stdio.h>#include<stdlib.h>#defineMcastaddr "233.0.0.1"//This example uses the multicast group address. #defineMcastport 5150//The local port number. #defineBUFSIZE 1024//send data buffer size. intMainintargcChar**argv) {Wsadata WSD;structsockaddr_in remote; SOCKET sock,sockm; TCHAR Sendbuf[bufsize]; intLen =sizeof(structsockaddr_in); //Initialize WinSock2.2   if(WSAStartup (Makeword (2,2), &AMP;WSD)! =0) {printf ("WSAStartup () failed\n"); return-1;} if(Sock=wsasocket (Af_inet,sock_dgram,0Null0, Wsa_flag_multipoint_c_leaf| Wsa_flag_multipoint_d_leaf|wsa_flag_overlapped)) ==invalid_socket) {printf ("Socket failed with:%d\n", WSAGetLastError ());  WSACleanup (); return-1;} //join a multicast groupremote.sin_family =af_inet; Remote.sin_port=htons (mcastport); Remote.sin_addr.s_addr=inet_addr (mcastaddr);if(sockm = Wsajoinleaf (sock, (sockaddr*) &Remote,sizeof(remote), Null,null,null,null, Jl_both)) ==invalid_socket) {printf ("wsajoinleaf () failed:%d\n", WSAGetLastError ());  Closesocket (sock);  WSACleanup (); return-1;} //sends multicast data and exits when the user enters "quit" in the console.     while(1) {printf ("SEND:"); scanf ("%s", SENDBUF); if(SendTo (SOCKM, (Char*) Sendbuf,strlen (SENDBUF),0,(structsockaddr*)&remote,sizeof(remote)) ==socket_error) {printf ("SendTo failed with:%d\n", WSAGetLastError ());   Closesocket (SOCKM);   Closesocket (sock);   WSACleanup (); return-1; }if(strcmp (SendBuf,"QUIT")==0) Break; Sleep ( -); } closesocket (SOCKM); Closesocket (sock); WSACleanup (); return 0;}
Iv. Summary

In this example, the IP multicast communication is discussed, the instance program is composed of sender and receiver, sender user input Multicast data from the console, receiver end requests to join the same multicast group, complete receiving sender sent multicast data.

Visual C + + implements LAN IP multicast

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.