TCP/IP network Programming Learning note _15--Multicast and broadcast

Source: Internet
Author: User
Tags htons

In this case, network radio may need to transmit the same data to tens of thousands of users at the same time, which is certainly unreasonable if it is transmitted once per user in the form of transmission we have previously spoken. Therefore, multicast technology is introduced to solve this problem, it can send the same data to a large number of users at the same time. The basic principle is this: there is a multicast group, as long as it joins all the customer service side of the group, the server sends the data they can receive, the specific transmission to the multicast group of each customer is routed by the route (if the router does not support multicast or network congestion, the implementation of multicast will also use tunneling technology).

Multicast
    • The data transmission characteristics of multicast are as follows:
      1, the multicast server side for a specific multicast group, only 1 times the data, all the customer service in the group can receive data.
      2, the number of multicast groups can be arbitrarily increased within the IP address range.

    • To set the time-to-live and join a multicast group
      1, set the time-to-live: refers only to the distance sent by the service end of the packet, expressed as an integer, and every 1 routers will be reduced by 1, when 0 o'clock, the packet can no longer be passed, can only be destroyed. Therefore, this value is set too general to affect network traffic. Of course, setting too small will not be delivered to the target (via socket option settings, which are used in the sample code).

      2, join the multicast group: Also through the socket can be set, the example code has the use method, here only introduces the multicast group structure body ip_mreq.

      struct IP_MREQ
      {
      struct IN_ADDR imr_multiaddr; IP address of the multicast group
      struct IN_ADDR imr_interface; Added customer service Host IP address
      }

    • Implementing multicast
      1, Sender (sender)

////Main.cpp//Hello_server////Created by app05 on 15-9-7.//Copyright (c) 2015 APP05. All rights reserved.//#include <stdio.h>#include <stdlib.h>#include <string.h>#include <unistd.h>#include <arpa/inet.h>#include <sys/socket.h>#define TTL //Packet lifetime, which can be passed up to the 64th route when destroyed #define Buf_sizevoidError_handling (Char*message);intMainintargcConst Char* argv[]) {intSend_sock;structSockaddr_in Mul_adr;intTime_live = TTL; FILE *FP;CharBuf[buf_size];if(ARGC! =3) {printf("Usage:%s <GroupIp> <Port> \ n", argv[0]);Exit(1); }//UDP-based multicastSend_sock = socket (pf_inet, SOCK_DGRAM,0);memset(&mul_adr,0,sizeof(MUL_ADR));    mul_adr.sin_family = af_inet; MUL_ADR.SIN_ADDR.S_ADDR = inet_addr (argv[1]); Mul_adr.sin_port = htons (Atoi (argv[2]));//Set the time-to-live (except here for other basic and UDP writing)SetSockOpt (Send_sock, Ipproto_ip, Ip_multicast_ttl, (void*) &time_live,sizeof(time_live));if(fp = fopen ("/users/app05/desktop/test.txt","R")) = = NULL) error_handling ("fopen () Error"); while(!feof (FP))//Returns a value other than 0 if the file ends, otherwise 0{fgets (buf, Buf_size, FP); SendTo (Send_sock, buf,strlen(BUF),0, (structSOCKADDR *) &mul_adr,sizeof(MUL_ADR)); Sleep1);//Just to add a transfer data time interval, no special meaning} fclose (FP); Close (Send_sock);return 0;}voidError_handling (Char*message) {fputs(message, stderr); FPUTC (' \ n ', stderr);Exit(1);}

2, Recipient (receiver)

////Main.cpp//Hello_client////Created by app05 on 15-9-7.//Copyright (c) 2015 APP05. All rights reserved.//#include <stdio.h>#include <stdlib.h>#include <string.h>#include <unistd.h>#include <arpa/inet.h>#include <sys/socket.h>#define Buf_sizevoidError_handling (Char*message);intMainintargcConst Char* argv[]) {intRecv_sock;intStr_len;CharBuf[buf_size];structSOCKADDR_IN ADR;structIp_mreq Join_adr;//Multicast Group structure    if(ARGC! =3)    {printf("Usage:%s <GroupIp> <Port> \ n", argv[0]);Exit(1); } Recv_sock = socket (pf_inet, SOCK_DGRAM,0);memset(&adr,0,sizeof(ADR));    adr.sin_family = af_inet;    ADR.SIN_ADDR.S_ADDR = htonl (Inaddr_any); Adr.sin_port = htons (Atoi (argv[2]));if(Bind (Recv_sock, (structSOCKADDR *) &adr,sizeof(ADR)) == -1) Error_handling ("bind () Error");//Join a multicast groupJOIN_ADR.IMR_MULTIADDR.S_ADDR = inet_addr (argv[1]);    JOIN_ADR.IMR_INTERFACE.S_ADDR = htonl (Inaddr_any); SetSockOpt (Recv_sock, Ipproto_ip, Ip_add_membership, (void*) &join_adr,sizeof(JOIN_ADR)); while(1) {Str_len = Recvfrom (Recv_sock, buf, Buf_size-1,0Null0);//Only need multicast group IP address, do not care about its host address        if(Str_len <0) Break; Buf[str_len] =0;fputs(buf, stdout); } close (Recv_sock);return 0;}voidError_handling (Char*message) {fputs(message, stderr); FPUTC (' \ n ', stderr);Exit(1);}

Broadcasting

Broadcast is functionally the same as multicasting, and it is possible to pass data to a large number of customers at the same time. But they differ in network scope, multicast can span different networks, so long as the multicast group is added to receive data. However, broadcasts can only transfer data to hosts in the same network.
Broadcast is divided into: Direct broadcast and local broadcast, direct broadcast sender's IP address only need to specify the network address, the host address all fill 255. This allows all hosts in this network address to receive the data. The IP address of the local broadcast sender is 255.255.255.255, so that all hosts on the local network can receive the data.

Setting the So_broadcast option to 1 means that the socket broadcast feature is turned on, which is turned off by default.
int bcast = 1;
SetSockOpt (Send_sock, Sol_socket, So_broadcast, (void *) &bcast, sizeof (bcast));

The following is a slight modification of the multicast code example, as shown in the local broadcast example:

////Main.cpp//Hello_server////Created by app05 on 15-9-7.//Copyright (c) 2015 APP05. All rights reserved.//#include <stdio.h>#include <stdlib.h>#include <string.h>#include <unistd.h>#include <arpa/inet.h>#include <sys/socket.h>#define TTL //Packet lifetime, which can be passed up to the 64th route when destroyed #define Buf_sizevoidError_handling (Char*message);intMainintargcConst Char* argv[]) {intSend_sock;structSockaddr_in Mul_adr;intTime_live = TTL; FILE *FP;CharBuf[buf_size];if(ARGC! =3) {printf("Usage:%s <GroupIp> <Port> \ n", argv[0]);Exit(1); }//UDP-based multicastSend_sock = socket (pf_inet, SOCK_DGRAM,0);memset(&mul_adr,0,sizeof(MUL_ADR));    mul_adr.sin_family = af_inet; MUL_ADR.SIN_ADDR.S_ADDR = inet_addr (argv[1]); Mul_adr.sin_port = htons (Atoi (argv[2]));//Set the time-to-live (except here for other basic and UDP writing)    //setsockopt (Send_sock, Ipproto_ip, Ip_multicast_ttl, (void *) &time_live, sizeof (time_live));    /*add: Broadcast Modification Office */    //The default socket is to turn off the broadcast, which is turned on as follows:    intSO_BRD =1;//Set to 1 to turn on broadcastSetSockOpt (Send_sock, Sol_socket, So_broadcast, (void*) &AMP;SO_BRD,sizeof(SO_BRD));if(fp = fopen ("/users/app05/desktop/test.txt","R")) = = NULL) error_handling ("fopen () Error"); while(!feof (FP))//Returns a value other than 0 if the file ends, otherwise 0{fgets (buf, Buf_size, FP); SendTo (Send_sock, buf,strlen(BUF),0, (structSOCKADDR *) &mul_adr,sizeof(MUL_ADR)); Sleep1);//Just to add a transfer data time interval, no special meaning} fclose (FP); Close (Send_sock);return 0;}voidError_handling (Char*message) {fputs(message, stderr); FPUTC (' \ n ', stderr);Exit(1);}
////Main.cpp//Hello_client////Created by app05 on 15-9-7.//Copyright (c) 2015 APP05. All rights reserved.//#include <stdio.h>#include <stdlib.h>#include <string.h>#include <unistd.h>#include <arpa/inet.h>#include <sys/socket.h>#define Buf_sizevoidError_handling (Char*message);intMainintargcConst Char* argv[]) {intRecv_sock;intStr_len;CharBuf[buf_size];structSOCKADDR_IN ADR;//struct ip_mreq Join_adr;//multicast Group structure    if(ARGC! =2)    {printf("Usage:%s <GroupIp> <Port> \ n", argv[0]);Exit(1); } Recv_sock = socket (pf_inet, SOCK_DGRAM,0);memset(&adr,0,sizeof(ADR));    adr.sin_family = af_inet;    ADR.SIN_ADDR.S_ADDR = htonl (Inaddr_any); Adr.sin_port = htons (Atoi (argv[1]));if(Bind (Recv_sock, (structSOCKADDR *) &adr,sizeof(ADR)) == -1) Error_handling ("bind () Error");//Join a multicast group    //join_adr.imr_multiaddr.s_addr = inet_addr (argv[1]);    //join_adr.imr_interface.s_addr = htonl (inaddr_any);    //setsockopt (Recv_sock, Ipproto_ip, ip_add_membership, (void *) &join_adr, sizeof (JOIN_ADR));     while(1) {Str_len = Recvfrom (Recv_sock, buf, Buf_size-1,0Null0);//Only need multicast group IP address, do not care about its host address        if(Str_len <0) Break; Buf[str_len] =0;fputs(buf, stdout); } close (Recv_sock);return 0;}voidError_handling (Char*message) {fputs(message, stderr); FPUTC (' \ n ', stderr);Exit(1);}

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

TCP/IP network Programming Learning note _15--Multicast and broadcast

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.