IP multicast (also known as multicast or multicast or multicast) technology is a TCP / IP network that allows one or more hosts (multicast sources) to send a single data package to multiple hosts (once, at the same time) technology. Multicast as a point-to-multi-point communication is one of the effective methods of saving network bandwidth. In the application of network audio / video broadcasting, when needed to transfer a node to multiple nodes, whether it is using a repeating point-to-point communication mode, or use a broadcast mode, it will be severely wasted network bandwidth, only multicast is the best s Choice. Multicast enables one or more multicast sources only send packets to a specific multicast group, and only the host joining the multicast group can receive the packet. At present, IP multicast technology is widely used in network audio / video broadcast, AOD / VOD, network video conferencing, multimedia distance education, "push" technology (such as stock market, etc.) and virtual reality games.
First, IP multicast technology introduction
1. IP multicast address and multicast group IP multicast communication must depend on IP multicast addresses, which is a D IP address in IPv4, range from 224.0.0.0 to 239.255.255.255, and is divided into local link multicast addresses , Reserved multicast addresses and management permissions multicast addresses. Among them, the local link multicast address ranges from 224.0.0.0 to 224.0.0.0.255, which is the address that is reserved for routing protocols and other uses, and the router does not forward IP packets belonging to this range; the reserved multicast address is 224.0.1.0 ~ 238.255.255.255, can be used worldwide (such as Internet) or network protocol; administrative rights multicast addresses are 239.0.0.0-239.255.255.255, which can be used inside, similar to private IP addresses, can not be used for Internet, can limit more Broadcast range.
All hosts using the same IP multicast address receive a multicast packet constitute a host group, also known as multicast group. A multicast group member is changed at any time, and a host can join or leave the multicast group, and the number of multicast group members and the location of the location are not restricted. One host can also belong to several multicast groups. . In addition, hosts that do not belong to a multicast group can also send packets to the multicast group.
2. IP Multicast Technology Hardware Support To implement IP multicast communication, requests to support IP multicast between multicast source and recipients, both hubs, switches, and hosts need to support IP multicast. At present, IP multicast technology has been widely supported by hardware, software vendors.
(1) The host supports IP multicast communication, including Windows CE 2.1, Windows 95, Windows 98, Windows NT 4, and Windows 2000, etc., both hosts running these operating systems can perform IP multicast communication. In addition, newly produced NIC also provides support for IP multicast. (2) The hub and switch currently most hub, the switch simply transmits the multicast data as a broadcast to send reception, but some, high-end switches provide support for IP multicast. For example, an 802.1p or IGMP multicast filtering function is enabled on the 3COM SuperStack 3 Swith 3300 switch, which forwards the multicast packet for the port that has detected the IGMP packet. (3) Router multicast communication requires all routers between multicast source nodes and destination nodes to provide support for Internet Group Management Protocol (IGMP), multicast routing protocols such as PIM, DVMRP, etc.).
When a host wants to join a multicast group, the "Host Member Report" IGMP message notification multicast router is issued. When the multicast router receives data sent to that multicast group, it is forwarded to all multicast hosts. The multicast router will also periodically issue the "Host Member Query" IGMP message, query the multicast host to the subnet, if you find that a multicast group has no member, stop the data of the multicast group. In addition, when IGMP V2 hosts (such as Windows 98/2000 Computers) exit a multicast group, a "exiting group" IGMP message will be sent to the router to notify the router to stop forwarding the multicast group. But only when all hosts on the subnet exit a multicast group, the router stops the data of the multicast group to the subnet. Using multicast routing protocols, the router can establish multicast routing tables from multicast source nodes to all destination nodes, thereby implementing multicast packets between subnets. For example, PIM (protocol independently) is a multicast routing protocol, there are two types: sparse-mode and dense-mode. Taking the Cisco 2621 router as an example, the basic settings of enabling IP multicast forwarding function are as follows:
C2621 (config) # ip multicast-routing Start IP multicast, makes the router becomes a multicast router C2621 (config) # int F0 / 0 Configuring Fast Ethernet Port 0 C2621 (Config-IF) # ip Pim Dense-Mode (or Sparse-mode) Start PIM while activating the IGMP protocol C2621 (config-if) # int F0 / 1 Configuring Fast Ethernet Port 1 C2621 (config-if) # ip Pim Dense-Mode (or sparse-mode)
Second, the programming method of IP multicast application
In practical applications, programmers typically need to prepare the underlying network application to implement the underlying communication on the Internet, such as the functionality of the IP multicast communication. Preparation of the underlying network application typically wants to use the network data communication programming interface, while the network programming interface provided in different operating systems is different. If the network programming interface in the Microsoft Windows environment is Windows socket ( Windows socket, referred to as Winsock. Winsock provides programming interfaces under multiple communication protocols such as TCP / IP, IPX. Different Windows versions support different WINSOCK versions, with earlier versions such as Windows 95 itself only supports Winsock1.1 (16-bit) programming (you can support Winsock2.0), while Windows98, Windows NT4 .0, Windows 2000 directly supports Winsock 2.0 (32-bit). Winsock2.0 is the extension of Winsock1.1, except for the Winsock1.1 API, has defined a set of protocol-independent APIs that support IP multicast.
Using Winsock 2.0 to implement IP multicast, the general steps are as follows:
1. Initializing Winsock Resources must call the WSAStartup () function to initialize the Windows Sockets DLL before using Winsock. It allows applications or DLL to specify versions required by the Windows Sockets API.
2. Creating a socket calling a wsasocket () function can create a socket using the UDP protocol, which is the initial sleeve of the multicast group, and the transmission and reception of the data will be performed on the socket. For IP multicast communication, parameter dwflags can be set to WSA_FLAG_MULTIPOINT_C_LEAF, WSA_FLAG_MULTIPOINT_D_LEAF and WSA_FLAG_OVERLAPPED bits, indicating that IP multicast communication is "no root" at the control level and data level, only the leaf node, they can join one Multicast group, and data sent from a leaf node will be transmitted to each leaf node (including itself); created sockets have overlap properties. 3. Setting the set of sockets Call the setSockOpt () function Sets the SO_REUSEADDR option for the socket to allow the socket to be tied to a already used address.
4. Binding socket calls the bind () function binding socket to link the created socket to the local address and the local port. For multicast communication, sending and receiving data typically use the same port.
5. Setting the mode WSAIOCTL () function of the mode WSAIOCTL () function of the multicast socket, is used to allow or disable the communication traffic sent by the multicast communication whether the communication flow transmitted will also be received on the same socket (ie, the multicast returns). It is worth noting that in Windows 95/98 / NT 4, the default is to allow multicast to return, but cannot be set, otherwise it will be erroneous; only in Windows 2000 or more, can set Allow / prohibit multicast returns. The WSAIOCTL () function command code SiO_Multicast_scope is used to set the range of multicast propagation, that is, the survival time TTL. Whenever the multicast router forwards the multicast packet, the TTL value in the packet will be reduced. If the TTL of the packet is reduced to 0, the router will discard the packet. The value of TTL is how much, and multicast data can pass through how many multicast routers. For example, the TTL value is 0, then multicast can only spread between multiple sockets of the local host, and cannot propagate to the "network cable"; the TTL value is 1 (default), the multicast data encounters the first The router will be discarded by it "ruthlessly", and is not allowed to pass the local network, that is, only multicast group members in the same network can receive multicast data.
6. Add a multicast group to call the wsajoinleaf () function to join a multicast group and specify a role (sender / recipient). When calling, the parameter dwflags specifies the socket as the sender (JL_Sender_only), the recipient (JL_Receiver_only) or both (jl_both). After the call is successful, a multi-broadcast set will be returned, and the closesocket () function closes the socket, leaving the multicast group, at which point the wsajoinleaf () function can be called again to join the multicast group. Note that the reception and transmission of multicast group data cannot be completed on the socket.
7. Sending data to multicast groups to send a sendTO () function to send multicast data to the specified multicast group on the specified UDP socket. When the call is called, the parameter TO should point to the IP address of the multicast group. It is worth noting that if an application just intends to send data to the multicast group, you don't have to join a multicast group.
8. Waiting for the event to call the wsaasyncselect () function, place the socket in non-blocking mode, and the application can receive a web event notification based on Windows messages on this socket. For example, if the parameter LEVENT value is fd_read, the application can receive a notification of "data is waiting to be read" on the socket. 9. The RecVFrom function is called from the multicast group to read the input data on the specified UDP socket. The transmission and reception of the data in multicast communication are generally used, so the transmission socket is the same as the receiving socket. 10. Close the socket and release the Winsock resources. After the end of the multicast communication, the closesocket () function is first turned off the multicast set and the UDP socket, and then call the WSacleanup () function to end the use of Windows Sockets DLL.
Third, the application example
In order to illustrate the application method of IP multicast technology, I designed a simple Windows socket 2 IP multicast application in Visual C . NET environment, by this reader can master the general method of IP multicast application design. The specific design method of the program is as follows:
1. Create a dialog-based MFC project CMULTICASTSOCKET in Visual Studio.net. Note Do not select "Windows Sockets" in the Advanced Features settings because MFC only supports Windows Socket 1 without support Windows Socket 2. In order to be programmed using Winsock 2 API, "Winsock2.h" header file should be included in the program and add WS2_32.lib's static library, which should be set in "Limited" / "Input" of the project properties. / "Additional dependencies".
2. In the dialog (Class CCMulticastSocketDLG) resource, set its CAPTION to "Winsock 2 Multicast Application" and add the following controls:
Static text: CAPTION is "received information:"; edit box: ID is IDC_Recher_Edit, read only, auto vscroll, vertical scroll and multiline property value is true static text: CAPTION is "Send information:" Edit box: ID For IDC_send_edit first button: caption is "Add Multicast Group (& J)", ID is IDC_JOIN_BUTTON second button: CAPTION is "Multicast Send (& S)", ID is IDC_SEND_BUTTON third button: caption is "left Multicast group (& L) ", ID is IDC_LEAVE_BUTTON fourth button: caption is" Exit (& Q) ", IDC_Quit_Button
Add a corresponding message processing function to the two edit boxes, add a corresponding message processing function to the four buttons; add timer messages to the dialog box (for timing display received) and its message processing function.
3. Add a new dialog resource, set its CAPTION to "Add Multicast Group", hold the default two button control, and add the following control:
Static text: CAPTION is "IP Multicast Group Address:" Edit Box: ID is IDC_IPAddress_edit Static Text: CAPTION is "IP Multicast Port:" Edit Box: ID is IDC_Port_EDit Static Text: CAPTION is "Survive Time:" Edit box: ID is IDC_TTL_EDIT check box: caption is "Multicast Return:", ID is IDC_LOOPBACK_CHECK, the Left text property value is TRUE. Add a new class CJOINGROUPDLG to the dialog, its base class is CDIALOG, then add associated variables to the three edits in the dialog, csting m_ipaddress, uint m_nport, uint m_nttl; to check box Add Variables of the associated BOOL type M_LoopBack.
4. Add cjoingroupdlg's header files in front of the cmulticastsocketdlg.h file: #include "joingroupdlg.h" and add a CJOINGROUPDLG class instance object M_JOINDLG in the CCMulticastSocketDLG class.
5. In order to receive network event notifications in the dialog, a user-defined message and message processing function should be added, and the specific implementation method is as follows: #DEFINE WM_SOCK_MSG (WM_USER 166) in the cmulticastsocketdlg.h file: #define wm_swm 166) Description afx_msg message handling function block: afx_msg LRESULT OnSocketMsg (WPARAM wParam, LPARAM lParam); CMulticastSocketDlg.cpp message block map file using ON_MESSAGE (WM_SOCK_MSG, OnSocketMsg) macro mapping message to the message handler, And specifically implement message processing function: LRESULT CCMULTICSTSOCKETDLG :: OnsetMsg (WPARAM WPARAM, LPARAM LPARAM) {...}.
The primary code of the program can be found in the program list, and the relevant function details can be found in the Microsoft MSDN Help System. In order to save space, the code is omitted in the program, and the code that is automatically generated and used for error handling is omitted.
Program list:
// cmulticastsocketdlg.cpp: Implement file #include "stdafx.h" #include "winsock2.h" #include "cmulticastsocket.h" #include "cmulticastsocketdlg.h" ... DWORD CBRET; SOCKET SOCK, SOCKM; File: // UDP socket, multicast socket BOOL BFLAG, BJOIN; SOCKADDR_IN LOCAL, REMOTE, FROM; File: // points to local, multicast groups, and data sources, IP address and port INT from Fromlen; Char ReceiveBuf [32000]; file: // buffer receiving BOOL bDataReceived; ...... BEGIN_MESSAGE_MAP (CCMulticastSocketDlg, CDialog) ...... ON_BN_CLICKED (IDC_JOIN_BUTTON, OnBnClickedJoinButton) ON_BN_CLICKED (IDC_LEAVE_BUTTON, OnBnClickedLeaveButton) ON_BN_CLICKED (IDC_QUIT_BUTTON, OnBnClickedQuitButton) ON_BN_CLICKED (IDC_SEND_BUTTON, OnBnClickedSendButton) ON_WM_TIMER () ON_MESSAGE (WM_SOCK_MSG , OnSocketMsg) END_MESSAGE_MAP () BOOL CCMulticastSocketDlg :: OnInitDialog () {CDialog :: OnInitDialog (); ...... SetTimer (1,100, NULL); file: // set the timer fromlen = sizeof (From); bDataReceived = TRUE; bJoin = False; return true; // unless the focus of the control is set, returns true} ... void ccmulticastsocketdlg :: OnbnclicKedJoinButton () file: // Add multicast group {if (m_joindlg.domodal () == idok) {Word WVersionr Equested; WSADATA WSADATA; INT Beijing Zhongqing; WVersionRequested = MakeWord (2, 2); Beijing Zhongqing = WSAStartup (WversionRequested, & WSADATA); File: // Initializing Winsock2 Resources IF (Beijing Zhongqing! = 0) {AFXMESSAGEBOX (" Cannot load Windows socket dynamic link library, MB_OK "); return (})! = 2 || Hibyte (wsadata.wversion)! = 2) {AFXMessageBox (" Winsock DLL does not support version 2.0 , MB_OK "); WSACleanup (); return;} file: // create a socket Sock = WSASocket (AF_INET, SOCK_DGRAM, IPPROTO_UDP, (LPWSAPROTOCOL_INFO) NULL, 0, WSA_FLAG_OVERLAPPED | WSA_FLAG_MULTIPOINT_C_LEAF | WSA_FLAG_MULTIPOINT_D_LEAF);
Bflag = true; file: // Sets the socket option to make the socket to reusable port address setsockopt (Sock, Sol_Socket, SO_REUSEADDR, (CHAR *) & bflag, sizeof (bflag));
File: // Bind the socket to the user specified port and default interface MEMSET (& local, 0, sizeof (local)); local.sin_family = AF_INET; local.sin_port = htons (ushort) m_jointlg.m_nport; Local.sin_addr.s_addr = htonl (INADDR_Addr_Any); Bind (Struct SockAddr Far *) & local, sizeof (local)); file: // Setup multicast datagram propagation range (Survival TTL) WSAIOCTL (SOCK, SIO_MULTICAST_SCOPE , & m_JoinDlg.m_nTTL, sizeof (int), NULL, 0, & cbRet, NULL, NULL); file: // set the multicast return (LOOKBACK) BOOL nLoopBack = m_JoinDlg.m_Loopback; WSAIoctl (Sock, SIO_MULTIPOINT_LOOPBACK, & nLoopBack, sizeof (nLoopBack ), NULL, 0, & CBRET, NULL, NULL);
memset (& Remote, 0, sizeof (Remote)); Remote.sin_family = AF_INET; Remote.sin_addr.s_addr = inet_addr (m_JoinDlg.m_IPAddress); Remote.sin_port = htons (m_JoinDlg.m_nPort); file: // added to the specified Multicast group and designated as both the sender as a recipient (JL_BOTH) Sockm = WSAJOINLEAF (Sock, (SockAddr *) & Remote, Sizeof (Remote), Null, Null, Null, Null, JL_BOTH; WSAASYNCSELECT (SOCK, M_HWND, WM_SOCK_MSG, FD_READ); File: // Register Network Message and Its Network Event Bjoin = true;}}
void CCMulticastSocketDlg :: OnBnClickedSendButton () file: // multicast transmission {if (bJoin) {UpdateData (TRUE); const char * strMessage = LPCTSTR (m_SendMessage); int nSize = m_SendMessage.GetLength () 1; sendto (Sock, StrMessage, nsize, 0, (sockaddr *) & remote, sizeof (transote));} else afxMessageBox ("Please join the multicast group!"); m_sendMessage = ""; Updatedata (false);}
void CCMulticastSocketDlg :: OnBnClickedLeaveButton () {file: // leave the multicast group closesocket (SockM); closesocket (Sock); WSACleanup (); m_SendMessage = ""; m_ReceiveMessage = ""; bDataReceived = TRUE; bJoin = FALSE; UpdateData ( False);
Void ccmulticastsocketdlg :: OnbnclickedQuitButton () {file: // Exited DESTROYWINDOW ();
void CCMulticastSocketDlg :: OnTimer (UINT nIDEvent) file: // timer handler, to achieve timing update information received {if (bDataReceived) {m_ReceiveMessage = ReceiveBuf; m_ReceiveMessage = "/ r / n"; bDataReceived = FALSE; UpdateData (FALSE );} CDialog :: OnTimer (nIDEvent);} LRESULT CCMulticastSocketDlg :: OnSocketMsg (WPARAM wParam, LPARAM lParam) {file: // retrieve network event switch (WSAGETSELECTEVENT (lParam)) {case FD_READ: recvfrom (Sock, receiveBuf, 32000 , 0, (SockAddr *) & from, & fromlen; bdatareceived = true; file: // Settings have been received to receive a message flag Break;} return true;}