UDP unicast, broadcast and multicast

This article is reproduced from: https://www.cnblogs.com/lidabo/p/5865045.html Author: lidabo Please indicate the statement when reprinting.

     There is no need to suggest a connection prior to the transmission of information using the UDP protocol. In other words, the client sends information to the server. The client only needs to give the ip address and port number of the server, and then encapsulate the information into a message to be sent and send it out. As for whether the server exists, or whether it can receive the message, the client does not care at all.     

     Unicast is used for end-to-end communication between two hosts, and broadcast is used for data communication from one host to all hosts on the entire local area network. Unicast and broadcast are two extremes, either communicating to one host or communicating to hosts on the entire LAN. In practice, it is often necessary to communicate to a specific set of hosts, rather than all hosts on the entire LAN, and this is what multicast is for.

  Usually the udp programs we discuss are all one-to-one unicast programs. This chapter will discuss one-to-many services: broadcast, multicast. For broadcasts, all hosts in the network receive a copy of the data. With multicast, the message is simply sent to a multicast address, and the network knows to distribute the data to hosts that say they want to receive data sent to that multicast address. In general, only UDP sockets allow broadcast or multicast.

1. UDP broadcast

  The difference between broadcast UDP and unicast UDP is that the IP address is different. Broadcast uses the broadcast address 255.255.255.255 to send messages to every host on the same broadcast network. It is worth emphasizing that local broadcast information will not be forwarded by routers . Of course, this is very easy to understand, because if the router forwards the broadcast information, it will inevitably cause network paralysis. This is why the designers of the IP protocol deliberately did not define an Internet-wide broadcast mechanism.

Broadcast addresses are often used in online games to communicate status information and the like between players on the same local network.

  In fact, as the name implies, broadcasting wants to talk to all the people in the local area network, but broadcasting still needs to specify the port number of the receiver , because it is impossible for all ports of the receiver to listen to the broadcast.

UDP server code:

copy code
 1 #include<iostream>
2 #include<stdio.h>
3 #include<sys/socket.h>
4 #include<unistd.h>
5 #include<sys/types.h>
6 #include<netdb.h>
7 #include<netinet/in.h>
8 #include<arpa/inet.h>
9 #include<string.h>
10 using namespace std;
11 int main()
12 { 13 setvbuf(stdout,NULL,_IONBF,0);14 fflush(stdout);15 int sock=-1;16 if((sock=socket(AF_INET,SOCK_DGRAM,0))==-1)17 { 18 cout<<"sock error"<<endl;19 return -1;20 }21 const int opt=-1;22 int nb=0;










23 nb=setsockopt(sock,SOL_SOCKET,SO_BROADCAST,(char*)&opt,sizeof(opt));//Set socket type
24 if(nb==-1)
25 { 26 cout<<"set socket error. ..\n"<<endl; 27 return -1; 28 } 29 struct sockaddr_in addrto; ​​30 bzero(&addrto,sizeof(struct sockaddr_in)); 31 addrto.sin_family=AF_INET; 32 addrto.sin_addr.s_addr=htonl(INADDR_BROADCAST );//The socket address is the broadcast address 33 addrto.sin_port=htons(6000);//The socket broadcast port number is 6000 34 int nlen=sizeof(addrto); 35 while(1) 36 { 37 sleep( 1); 38 char msg[]={"the message broadcast"}; 39 int ret=sendto(sock,msg,strlen(msg),0,(sockaddr*)&addrto,nlen);//publish message to broadcast address














40 if(ret<0)
41 { 42 cout<<"send error...\n"<<endl;43 return -1;44 }45 else 46 { 47 printf("ok\n");48 }49 }50 return 0;51 }









copy code

 UDP broadcast client code:

copy code
 1 #include<iostream>
2 #include<stdio.h>
3 #include<sys/socket.h>
4 #include<unistd.h>
5 #include<sys/types.h>
6 #include<netdb.h>
7 #include<netinet/in.h>
8 #include<arpa/inet.h>
9 #include<string.h>
10
11
12 using namespace std;
13 int main()
14 { 15 setvbuf(stdout,NULL,_IONBF,0);16 fflush(stdout);17 struct sockaddr_in addrto;18 bzero(&addrto,sizeof(struct sockaddr_in));19 addrto.sin_family=AF_INET;20 addrto.sin_addr.s_addr=htonl(INADDR_ANY);21 addrto.sin_port=htons(6000);







22 socklen_t len=sizeof(addrto);
23 int sock=-1;
24 if((sock=socket(AF_INET,SOCK_DGRAM,0))==-1)
25 { 26 cout<<"socket error..."<<endl;27 return -1;28 }29 const int opt=-1;30 int nb=0;31 nb=setsockopt(sock,SOL_SOCKET,SO_BROADCAST,(char*)&opt,sizeof(opt));32 if(nb==-1)33 { 34 cout<<"set socket errror..."<<endl;35 return -1;36 }37 if(bind(sock,(struct sockaddr*)&(addrto),len)==-1)38 { 39 cout<<"bind error..."<<endl;














40 return -1;
41 }
42 char msg[100]={0};
43 while(1)
44 { 45 int ret=recvfrom(sock,msg,100,0,(struct sockaddr*)&addrto,&len);46 if(ret<=0)47 { 48 cout<<"read error..."<<endl;49 }50 else51 { 52 printf("%s\t",msg);53 }54 sleep(1);55 }56 return 0;57 }












copy code

 2. UDP multicast

1. The concept of multicast (multicast)

  Multicast, also known as "multicast", logically groups hosts of the same service type in the network. When data is sent and received, the data is only carried out in the same group, and other hosts cannot send and receive the corresponding data without joining this group. data.

  When broadcasting on the WAN, the switches and routers in it only copy and forward the data to the host that needs to get the data. A host can request a router to join or leave a group. The routers and switches in the network selectively copy and transmit data, and transmit the data only to the hosts in the group. This feature of multicasting allows data to be sent to multiple hosts at a time without affecting other communications from other hosts that do not need to (not join the group).

Compared with traditional one-to-one unicast, multicast has the following advantages:

  1. Hosts with the same service join the same data stream and share the same channel, which saves the advantages of bandwidth and server, and has the advantages of broadcasting without the bandwidth required for broadcasting.

  2. The total bandwidth of the server is not limited by the bandwidth of the client. Since the multicast protocol determines whether to forward the data stream according to the needs of the receiver, the bandwidth on the server side is constant and has nothing to do with the number of clients.

  3. Like unicast, multicast is allowed to transmit on the wide area network, namely the Internet, while broadcast can only be carried out on the same local area network.

Disadvantages of multicast:

  1. Compared with unicast, multicast has no error correction mechanism, and it is difficult to make up for errors when errors occur, but this function can be implemented at the application layer.

  2. There are defects in multicast network support, which requires the support of routers and network protocol stacks.

  3. The applications of multicast mainly include online video, online conference and so on.

2. Multicast over WAN

  Multicast addresses are specific, and class D addresses are used for multicast. Class D IP addresses are multicast IP addresses, that is, IP addresses between 224.0.0.0 and 239.255.255.255, and are divided into three types: local connection multicast addresses, reserved multicast addresses, and management authority multicast addresses:

  1. Local multicast address: between 224.0.0.0 and 224.0.0.255. This is an address reserved for routing protocols and other purposes. The router does not forward IP packets that belong to this range.

  2. Reserved multicast address: between 224.0.1.0 and 238.255.255.255, which can be used for global scope (such as Internet) or network protocol.

  3. Multicast address for management authority: between 239.0.0.0 and 239.255.255.255, which can be used within the organization, similar to a private IP address, cannot be used for the Internet, and can limit the scope of multicast.

  Multicast programming is implemented using setsockopt() and getsockopt() functions. Multicast options are at the IP layer. See 11.5 for the option values ​​and meanings.

                                  Table 11.5 Multicast related options

Options for getsockopt()/setsockopt()

meaning

IP_MULTICAST_TTL

Set the TTL value of multicast group data

IP_ADD_MEMBERSHIP

Join a multicast group on a specified interface

IP_DROP_MEMBERSHIP

Exit the multicast group

IP_MULTICAST_IF

Get default interface or set interface

IP_MULTICAST_LOOP

Disable multicast data loopback

3. Multicast programming framework

To perform multicast programming, you need to follow a certain programming framework. Multicast program framework mainly includes socket initialization, setting multicast timeout, joining multicast group, sending data, receiving data and leaving from multicast group. The steps are as follows:

(1) Create a socket.

(2) Then set the parameters of multicast, such as timeout time TTL, local loopback permission LOOP, etc.

(3) Join the multicast group.

(4) Send and receive data.

(5) Leave from the multicast group.

4. Multicast implementation code

Server code:

copy code
 1 #include<iostream>
2 #include<stdio.h>
3 #include<sys/socket.h>
4 #include<netdb.h>
5 #include<sys/types.h>
6 #include<arpa/inet.h>
7 #include<netinet/in.h>
8 #include<unistd.h>
9 #include<stdlib.h>
10 #include<string.h>
11 #define MCAST_PORT 8888
12 #define MCAST_ADDR "224.0.0.88" // 多播地址
13 #define MCAST_DATA "BROADCAST TEST DATA" // 多播内容
14 #define MCAST_INTERVAL 5 //多播时间间隔
15 using namespace std;
16
17 int main()
18 { 19 int sock;20 struct sockaddr_in mcast_addr;21 sock=socket(AF_INET,SOCK_DGRAM,0);22 if(sock==-1)




23 { 24 cout<<"socket error"<<endl;25 return -1;26 }27 memset(&mcast_addr,0,sizeof(mcast_addr));28 mcast_addr.sin_family=AF_INET;29 mcast_addr.sin_addr.s_addr=inet_addr(MCAST_ADDR);30 mcast_addr.sin_port=htons(MCAST_PORT);31 while(1)32 { //向局部多播地址发送多播内容33 int n=sendto(sock,MCAST_DATA,sizeof(MCAST_DATA),0,(struct sockaddr*)&mcast_addr,sizeof(mcast_addr));34 if(n<0)35 { 36 cout<<"send error"<<endl;37 return -2;38 }















39 else
40 { 41 cout<<"send message is going ...."<<endl;42 }43 sleep(MCAST_INTERVAL);44 45 }46 return 0;47 }






copy code

Client code:

copy code
1 #include<iostream> 
2 #include<stdio.h>
3 #include<stdlib.h>
4 #include<string.h>
5 #include<sys/types.h>
6 #include<unistd.h>
7 # include<sys/socket.h>
8 #include<netdb.h>
9 #include<arpa/inet.h>
10 #include<netinet/in.h>
11 #define MCAST_PORT 8888
12 #define MCAST_ADDR "224.0.0.88" /*A local connection multicast address, the router does not forward*/
13 #define MCAST_INTERVAL 5 //Sending interval
14 #define BUFF_SIZE 256 //Receive buffer size
15 using namespace std;
16 int main()
17 { 18 int sock; 19 struct sockaddr_in local_addr; 20 int err=-1; 21 sock=socket(AF_INET,SOCK_DGRAM,0);




22 if(sock==-1)
23 { 24 cout<<"sock error"<<endl;25 return -1;26 }27 /*初始化地址*/28 local_addr.sin_family=AF_INET;29 local_addr.sin_addr.s_addr=htonl(INADDR_ANY);30 local_addr.sin_port=htons(MCAST_PORT);31 /*绑定socket*/32 err=bind(sock,(struct sockaddr*)&local_addr,sizeof(local_addr));33 if(err<0)34 { 35 cout<<"bind error"<<endl;36 return -2;37 }38 /*设置回环许可*/39 int loop=1;
















40 err=setsockopt(sock,IPPROTO_IP,IP_MULTICAST_LOOP,&loop,sizeof(loop));
41 if(err<0)
42 { 43 cout<<"set sock error"<<endl; 44 return -3; 45 } 46 struct ip_mreq mreq;/*Join the broadcast group*/ 47 mreq.imr_multiaddr.s_addr=inet_addr(MCAST_ADDR);//Broadcast address 48 mreq.imr_interface.s_addr=htonl(INADDR_ANY); //The network interface is the default 49 /* Join the broadcast group*/ 50 err=setsockopt(sock,IPPROTO_IP,IP_ADD_MEMBERSHIP,&mreq,sizeof(mreq)); 51 if(err<0) 52 { 53 cout<<"set sock error"<<endl; 54 return -4 ;55 }56 int times=0;














57 socklen_t addr_len=0;
58 char buff[BUFF_SIZE];
59 int n=0;
60 /*Receive broadcast group messages in a loop, and exit after 5 times*/
61 for(times=0;;times++)
62 { 63 addr_len= sizeof(local_addr); 64 memset(buff,0,BUFF_SIZE); 65 n=recvfrom(sock,buff,BUFF_SIZE,0,(struct sockaddr*)&local_addr,&addr_len); 66 if(n==-1) 67 { 68 cout<<"recv error"<<endl; 69 return -5; 70 } 71 /*print message*/ 72 printf("RECV %dst message from server : %s\n",times,buff);










73 sleep(MCAST_INTERVAL);
74 }
75 /*退出广播组*/
76 err=setsockopt(sock,IPPROTO_IP,IP_DROP_MEMBERSHIP,&mreq,sizeof(mreq));
77 close(sock);
78 return 0;
79 }
copy code

 Analysis of the bind function here

  The bind operation first checks whether the port specified by the user is available, and then sets the correct value for some members of the socket and adds it to the hash table myudp_hash. Then, every time the protocol stack receives UDP data, it will check the source and destination addresses of the datagram, as well as the source and destination ports, find the matching socket in myudp_hash, and put the datagram into the receiving queue of the socket. for the user to read. In this program, the bind operation binds the socket to the address 224.0.0.88:8888. The immediate result of this operation is that, for the socket itself, the following values ​​are affected:
    struct inet_sock{         .rcv_saddr = 224.0.0.88;         .saddr = 0.0.0.0;         .sport = 8888;         .daddr = 0.0.0.0;         .dport = 0;     }     These five data indicate that the socket uses port 8888 locally when sending packets, and any network device can be used locally interface, and the destination address sent to is not specified. When receiving data, only data sent to port 8888 sent to IP address 224.0.0.88 is received.






My question? ? ?

Why must the port number of the broadcaster and the receiver be the same to receive the broadcast? I tried to open two clients on a linux machine, one of which is different from the port number of the broadcaster. This client can't receive the broadcast. Which netizen knows and please let me know.
    In the program, there is a setsockopt operation followed by bind. Its function is to add the socket to a multicast group. Because the socket needs to receive the data of the multicast address 224.0.0.1, it must join the multicast group.

3. UDP broadcast and unicast

broadcast vs unicast

  The processing process of broadcast and unicast is different. Unicast data is only processed by a specific host that sends and receives data, while broadcast data is processed by the entire local area network.

  For example, there are 3 hosts on an Ethernet, and the configuration of the hosts is shown in Table 11.4.

                                  Table 11.4 Configuration of hosts in a local area network

host

A

B

C

IP address

192.168.1.150

192.168.1.151

192.168.1.158

MAC address

00:00:00:00:00:01

00:00:00:00:00:02

00:00:00:00:00:03

  Unicast process: Host A sends a UDP datagram to host B, the destination IP is 192.168.1.151, the port is 80, and the destination MAC address is 00:00:00:00:00:02. This data passes through the UDP layer and the IP layer, and reaches the data link layer, and the data spreads over the entire Ethernet. In this layer, other hosts will determine the destination MAC address. The MAC address of host C is 00:00:00:00:00:03, which does not match the destination MAC address of 00:00:00:00:00:02. The data link layer will not process it and directly discard the data.

  The MAC address of host B is 00:00:00:00:00:02, which is consistent with the destination MAC address 00:00:00:00:00:02. This data will pass through the IP layer and the UDP layer to reach the application receiving the data program.

  Broadcast process: Host A sends broadcast data to the entire network, the destination IP is 192.168.1.255, the port is 80, and the destination MAC address is FF:FF:FF:FF:FF:FF. This data passes through the UDP layer and the IP layer, and reaches the data link layer, and the data spreads over the entire Ethernet. In this layer, other hosts will determine the destination MAC address. Since the destination MAC address is FF:FF:FF:FF:FF:FF, host C and host B will ignore the comparison of the MAC address (of course, if the protocol stack does not support broadcasting, the MAC address will still be compared), and process the received data .

  The processing process of host B and host C is the same. The data will pass through the IP layer and the UDP layer to reach the application receiving the data.

No pains , no gains. Fuel yourself and fight for the future.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=324074794&siteId=291194637