当前位置:网站首页>Broadcast, multicast, unicast
Broadcast, multicast, unicast
2022-07-24 01:00:00 【lhb2998658795】
One . radio broadcast
1.1 Concept
Home page socket There is only one receiver for Jianshao's packet sending method , be called unicast
If it is sent to all hosts in the LAN at the same time , be called radio broadcast
If it is sent to some hosts in the LAN , be called Multicast
Be careful : Only one sending method can be selected for the same socket .
User datagram only ( Use UDP agreement ) Socket to broadcast
1.2 Broadcast address
With 192.168.1.0 (255.255.255.0) Network segment as an example , The largest host address 192.168.1.255 The data packets sent to the address representing the broadcast address of the network segment are received by all hosts ,255.255.255.255 Represents the broadcast address in all network segments .
Broadcast can be sent to all hosts , Because of the broadcast mac Special address , For all ff, ip The address is also special , It is broadcast ip Address , Send such packets to the switch first , Then it is sent to all hosts by the switch . Every host in the LAN can receive this packet , With UDP For example , The network card receives this packet , Check the link layer first , Purpose of discovery mac The address is the broadcast address , You can use the , To the network layer , Find out ip The address is broadcast ip Address , It is also allowed to pass , To the transport layer , As long as the destination port number matches , Then you can call the application layer for processing .
1.3 Broadcasting process
sender :
Create socket socket( )
Set to allow sending broadcast permission setsockopt( )
Fill the broadcast information structure sockaddr_in
send data sendto( )
The receiver :
Create socket socket( )
Fill the broadcast information structure sockaddr_in
Bind the socket to the broadcast information structure bind( )
receive data recvfrom( )
1.4 The code realizes broadcasting
Code instructions : This code is to achieve a receive a send , The server receives , The client sends , The code is compared with the previous homepage socket It's almost a change in the way , Set up a broadcast , If you need to know , Please refer to the home page socket The article , Thank you for watching .
Set the way of broadcasting :
int on = 1;
setsockopt(sockfd, SOL_SOCKET, SO_BROADCAST, &on, sizeof(on));Server code
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netinet/ip.h>
#include <string.h>
#include <unistd.h>
#include <stdlib.h>
#include <arpa/inet.h>
#define ERRLOG(errmsg) do{\
printf("%s:%s:%d --", __FILE__, __func__, __LINE__);\
perror(errmsg);\
exit(-1);\
}while(0)
int main(int argc, const char *argv[]){
if(3 != argc){
printf("Usage : %s <ip> <port>\n", argv[0]);
return -1;
}
// Create user datagram socket
int sockfd = socket(AF_INET, SOCK_DGRAM, 0);
if(-1 == sockfd){
ERRLOG("socket error");
}
// Fill the broadcast information structure
struct sockaddr_in serveraddr;
memset(&serveraddr, 0, sizeof(serveraddr));
serveraddr.sin_family = AF_INET;
// The port number can be arbitrarily specified
serveraddr.sin_port = htons(atoi(argv[2]));
//ip The address must be broadcast ip Address
serveraddr.sin_addr.s_addr = inet_addr(argv[1]);
socklen_t serveraddr_len = sizeof(serveraddr);
// binding
if(-1 == bind(sockfd, (struct sockaddr *)&serveraddr, serveraddr_len)){
ERRLOG("bind error");
}
// Define the structure to save the information of the other party
struct sockaddr_in client_addr;
memset(&client_addr, 0, sizeof(client_addr));
socklen_t client_addr_len = sizeof(client_addr);
char buff[128] = {0};
// Receive data circularly
while(1){
if(-1 == recvfrom(sockfd, buff, 128, 0, (struct sockaddr *)&client_addr, &client_addr_len)){
ERRLOG("recvfrom error");
}
printf(" client [%s:%d] Send data [%s]\n", inet_ntoa(client_addr.sin_addr), ntohs(client_addr.sin_port), buff);
memset(buff, 0, 128);
}
close(sockfd);
return 0;
}Client code
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netinet/ip.h>
#include <string.h>
#include <unistd.h>
#include <stdlib.h>
#include <arpa/inet.h>
#define ERRLOG(errmsg) do{\
printf("%s:%s:%d --", __FILE__, __func__, __LINE__);\
perror(errmsg);\
exit(-1);\
}while(0)
int main(int argc, const char *argv[]){
if(3 != argc){
printf("Usage : %s <ip> <port>\n", argv[0]);
return -1;
}
// Create user datagram socket
int sockfd = socket(AF_INET, SOCK_DGRAM, 0);
if(-1 == sockfd){
ERRLOG("socket error");
}
// Fill the broadcast information structure
struct sockaddr_in serveraddr;
memset(&serveraddr, 0, sizeof(serveraddr));
serveraddr.sin_family = AF_INET;
// The port number can be arbitrarily specified
serveraddr.sin_port = htons(atoi(argv[2]));
//ip The address must be broadcast ip Address
serveraddr.sin_addr.s_addr = inet_addr(argv[1]);
socklen_t serveraddr_len = sizeof(serveraddr);
// Set to allow broadcasting
int on = 1;
if(-1 == setsockopt(sockfd, SOL_SOCKET, SO_BROADCAST, &on, sizeof(on))){
ERRLOG("setsockopt error");
}
char buff[128] = {0};
// Loop data
while(1){
fgets(buff, 128, stdin);
buff[strlen(buff)-1] = '\0';
if(-1 == sendto(sockfd, buff, 128, 0, (struct sockaddr *)&serveraddr, serveraddr_len)){
ERRLOG("sendto error");
}
memset(buff, 0, 128);
}
return 0;
}Two . Multicast
2.1 Concept
Unicast can only be sent to one receiver . Broadcast to all hosts . Too many broadcasts will take up a lot of network bandwidth , Cause a broadcast storm , Affect normal communication . Multicast ( Also known as multicast ) It's a compromise . Only hosts that join a multicast group can receive data . Multicast can be sent to multiple hosts , It can also avoid bringing too much load like broadcasting ( Each host must go to the transport layer to determine whether the broadcast packet needs to be processed ).
2.2 Multicast address
D Class address ( Multicast address ) Regardless of network address and host address , The first 1 Before byte 4 The bit is fixed to 1110
The address range of the anchor :224.0.0.1 – 239.255.255.255
2.3 Multicast process
sender :
Create socket socket( )
Fill the multicast information structure sockaddr_in
send data sendto( )
The receiver :
Create socket scoket( )
Fill the multicast information structure sockaddr_in
Bind the socket to the multicast information structure bind( )
Set to join the multicast group setsockopt( )
receive data recvfrom( )
2.3 Set join multicast group
// Use the following structure
struct ip_mreqn {
struct in_addr imr_multiaddr; /* Multicast group ip Address */
struct in_addr imr_address; /* Local ip Address */
int imr_ifindex; /* Interface index 0 Represents any interface */
};
struct ip_mreqn my_mreqn;
// fill
setsockopt(sockfd, IPPROTO_IP, IP_ADD_MEMBERSHIP, &my_mreqn, sizeof(my_mreqn));2.4 Code implementation
The server ( The receiver ):
#include <stdio.h>
#include <sys/types.h> /* See NOTES */
#include <sys/socket.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netinet/ip.h>
#include <string.h>
#include <unistd.h>
#include <stdlib.h>
#include <arpa/inet.h>
#define ERRLOG(errmsg) do{\
printf("%s:%s:%d --", __FILE__, __func__, __LINE__);\
perror(errmsg);\
exit(-1);\
}while(0)
int main(int argc, const char *argv[]){
if(3 != argc){
printf("Usage : %s <ip> <port>\n", argv[0]);
return -1;
}
// Create user datagram socket
int sockfd = socket(AF_INET, SOCK_DGRAM, 0);
if(-1 == sockfd){
ERRLOG("socket error");
}
// Fill the broadcast information structure
struct sockaddr_in serveraddr;
memset(&serveraddr, 0, sizeof(serveraddr));
serveraddr.sin_family = AF_INET;
// The port number can be arbitrarily specified
serveraddr.sin_port = htons(atoi(argv[2]));
//ip The address is multicast group ip Address !!!!!
serveraddr.sin_addr.s_addr = inet_addr(argv[1]);
socklen_t serveraddr_len = sizeof(serveraddr);
// Bind socket with Multicast information structure
if(-1 == bind(sockfd, (struct sockaddr *)&serveraddr, serveraddr_len)){
ERRLOG("bind error");
}
// Set join multicast group
struct ip_mreqn my_mreqn;
memset(&my_mreqn, 0, sizeof(my_mreqn));
my_mreqn.imr_multiaddr.s_addr = inet_addr(argv[1]);
my_mreqn.imr_address.s_addr = inet_addr("192.168.60.109");
my_mreqn.imr_ifindex = 0;// Any interface
if(-1 == setsockopt(sockfd, IPPROTO_IP, IP_ADD_MEMBERSHIP, &my_mreqn, sizeof(my_mreqn))){
ERRLOG("setsockopt error");
}
// Define the structure to save the information of the other party
struct sockaddr_in client_addr;
memset(&client_addr, 0, sizeof(client_addr));
socklen_t client_addr_len = sizeof(client_addr);
char buff[128] = {0};
// Receive data circularly
while(1){
if(-1 == recvfrom(sockfd, buff, 128, 0, (struct sockaddr *)&client_addr, &client_addr_len)){
ERRLOG("recvfrom error");
}
printf(" client [%s:%d] Send data [%s]\n", inet_ntoa(client_addr.sin_addr), ntohs(client_addr.sin_port), buff);
memset(buff, 0, 128);
}
close(sockfd);
return 0;
}client ( Send ):
#include <stdio.h>
#include <sys/types.h> /* See NOTES */
#include <sys/socket.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netinet/ip.h>
#include <string.h>
#include <unistd.h>
#include <stdlib.h>
#include <arpa/inet.h>
#define ERRLOG(errmsg) do{\
printf("%s:%s:%d --", __FILE__, __func__, __LINE__);\
perror(errmsg);\
exit(-1);\
}while(0)
int main(int argc, const char *argv[]){
if(3 != argc){
printf("Usage : %s <ip> <port>\n", argv[0]);
return -1;
}
// Create user datagram socket
int sockfd = socket(AF_INET, SOCK_DGRAM, 0);
if(-1 == sockfd){
ERRLOG("socket error");
}
// Fill the broadcast information structure
struct sockaddr_in serveraddr;
memset(&serveraddr, 0, sizeof(serveraddr));
serveraddr.sin_family = AF_INET;
// The port number can be arbitrarily specified
serveraddr.sin_port = htons(atoi(argv[2]));
//ip Address broadcast address
//224.0.0.1 ~ 239.255.255.255
serveraddr.sin_addr.s_addr = inet_addr(argv[1]);
socklen_t serveraddr_len = sizeof(serveraddr);
char buff[128] = {0};
// Loop data
while(1){
fgets(buff, 128, stdin);
buff[strlen(buff)-1] = '\0';
if(-1 == sendto(sockfd, buff, 128, 0, (struct sockaddr *)&serveraddr, serveraddr_len)){
ERRLOG("sendto error");
}
memset(buff, 0, 128);
}
return 0;
}边栏推荐
- mysql 分支语句case报错
- Pbootcms database conversion tutorial (SQLite to MySQL detailed tutorial)
- Hypothesis test of Pearson correlation coefficient
- Notes to Chapter 2 of kubernetes in action
- Tutorial on principles and applications of database system (039) -- MySQL query (I): syntax analysis of select command
- Dataframe.groupby learning materials
- Tutorial on the principle and application of database system (048) -- MySQL query (x): self connection query
- Tutorial on principles and applications of database system (051) -- MySQL query (XIII): using queries in DML statements
- J'ai choisi la mauvaise technologie au mauvais moment.
- How to use mitmproxy to get data return in automated testing?
猜你喜欢

Okaleido tiger NFT is about to log in to the binance NFT platform. Are you looking forward to it?

Introduction to several scenarios involving programming operation of Excel in SAP implementation project

The postman test interface has 404 or 500 errors when the URL is configured correctly

Intelligent video monitoring solutions for elderly care institutions, using new technologies to help the intelligent supervision of nursing homes

这是一道大水题

爬虫requests模块的基本使用

深入理解协程

Pbootcms database conversion tutorial (SQLite to MySQL detailed tutorial)

An article teaches you the basic use of kubernetes

制作 .Img 镜像文件
随机推荐
Interviewer: if the order is not paid within 30 minutes after it is generated, it will be automatically cancelled. How to realize it?
Chapter 1 water test --*offer
[flyway introduction]
Scroll view realizes drop-down refresh (to avoid the drop-down problem triggered by the initial refresh triggered value of true when onload enters the page)
Focus on microservices
OSI open system interconnection model and tcp/ip model
Establishment of static route
Are the top ten securities companies risky and safe to open accounts?
Tutorial on the principle and application of database system (046) -- MySQL query (VIII): group by
freemarker
Tutorial on principles and applications of database system (039) -- MySQL query (I): syntax analysis of select command
Analysis of the advantages of the LAAS scheme of elephant swap led to strong performance of ETOKEN
Three usages of synchronized keywords in vernacular
Static extension configuration
[the 83rd fortnight of leetcode]
Project scenario: NVIDIA SMI unable to datemine the device handle for GPU 0000:01:00.0: unknown error
Tutorial on the principle and application of database system (048) -- MySQL query (x): self connection query
The flare project celery uses the pits encountered in redis sentinel
Concurrent programming 1-2
Hot 100 dynamic programming