Linux Network Programming Notes broadcast introduction

Article directory

Reference resources

All the knowledge in this article refers to online courses:
https://study.163.com/course/courseLearn.htm?courseId=1002913013&share=1&shareId=1145943119#/learn/video?lessonId=1003301249&courseId=1002913013

1 socket options

Socket options are used to modify the behavior of sockets and their underlying communication protocols. The setsockopt and getsockopt functions let you view and set various options for sockets.
The following two functions return values: 0 for success and - 1 for error

int getsockopt(int sockfd,int level,int optname,
							void *optval,socklen_t *optlen);
int setsockopt(int sockfd,int level,int optname,
							const void *optval,socklen_t optlen);

1.1 parameter description

  • level

The parameter level identifies the protocol to which the option is applied. If the option is a general socket level option, then the level is set to sol "socket". Otherwise, level is set to the protocol number that controls this option. For the TCP option, level is ipproto? TCP, and for IP, level is ipproto? IP.

  • optname
    The following summarizes the general socket hierarchy options, that is, the parameter optname.
option Type of parameter optval describe
SO_ACCEPTCONN int The return message indicates whether the socket can be monitored (getsockopt only)
SO_BROADCAST int If * optval is not 0, broadcast data segment
SO_DEBUG int If * optval is not 0, enable network drive debugging
SO_DONTROUTE int If * optval is not 0, bypass the normal route
SO_ERROR int Returns the pending socket error and clears (getsockopt only)
SO_KEEPALIVE int If * optval is not 0, enable periodic keep alive message
SO_LINGER struct linger Delay time when there is still no message sent and the socket is closed
SO_OOBINLINE int If * optval is not 0, put out of band data in normal data
SO_RCVBUF int Byte length of receive buffer
SO_RCVLOWAT int Minimum number of data bytes returned in receive call
SO_RCVTIMEO struct timeval Timeout value for socket receive call
SO_REUSEADDR int If * optval is not 0, reuse the address in bind
SO_SNDBUF int Byte length of send buffer
SO_SNDLOWAT int Minimum number of bytes of data transferred in a send call
SO_SNDTIMEO struct timeval Timeout value for socket send call
SO_TYPE int Identify socket type (getsockopt only)
  • optval
    The optval parameter points to a data structure or an integer depending on the options. Some of the options are on/off switches. If the integer is not 0, the option is enabled. If the integer is 0, the option is disabled.
  • optlen
    The optlen parameter specifies the size of the object that optal points to.

1.2 so? Bradcast options

So ﹐ broadcast option controls whether UDP socket can send broadcast datagram. The type of option is int, non-zero means "yes". Note that only UDP socket can use this option, and TCP cannot use broadcast.

int opt = 1;
if((sockfd = socket(AF_INET,SOCK_DGRAM,0)) < 0){
	//error handling
}
if(setsockopt(sockfd,SOL_SOCKET,
					SO_BROADCAST,&opt,sizeof(opt)) < 0){
	//error handling
}

1.3 so? Sndbuf and so? Rcvbuf options

Each socket has a send buffer and a receive buffer, which are used by the underlying protocol. The receive buffer stores the data received by the protocol until it is read by the application program, and the send buffer stores the data written by the application until it is sent by the protocol. The so ﹣ sndbuf and so ﹣ rcvbuf options control the size of the send and receive buffers, respectively, and their types are int in bytes.

if((sockfd = socket(AF_INET,SOCK_STREAM,0)) < 0){
	//error handling
}

//Get the size of the send buffer stored in the opt parameter in the following program
if(getsockopt(sockfd,SOL_SOCKET,
					SO_SNDBUF,&opt,sizeof(opt)) < 0){
	//error handling
}
opt += 2048;
if(setsockopt(sockfd,SOL_SOCKET,
				SO_SNDBUF,&opt,sizeof(opt)) < 0){
	//error handling
}

2 broadcast address

  • If {net ID,subnet ID,host ID} is used to represent the IPV4 address, then there are four types of broadcast addresses. We use - 1 to represent the field where all bits are 1.
  • Subnet broadcast address: {net ID,subnet ID,-1}. This type of address arrangement specifies all interfaces on the subnet. For example, if we use an 8-bit subnet ID for class B address 192.168, then 192.168.2.255 will be the subnet broadcast address of all interfaces on the 192.168.2 subnet. Routers usually do not forward such broadcasts.

3 example

3.1 broadcast receiver

#include<sys/socket.h>
#include<arpa/inet.h>
#include<netdb.h>
#include<unistd.h>
#include<string.h>
#include<stdlib.h>
#include<stdio.h>
#include<signal.h>
#include<time.h>

int sockfd;

void sig_handler(int signo){
	if(signo == SIGINT){
		printf("receiver will exited\n");
		close(sockfd);
		exit(1);
	}
}

int main(int argc,char *argv[]){
	if(argc < 2){
		fprintf(stderr,"usage:%s port\n",argv[0]);
		exit(1);
	}

	if(signal(SIGINT,sig_handler) == SIG_ERR){
		perror("signal sigint error");
		exit(1);
	}

	sockfd = socket(AF_INET,SOCK_DGRAM,0);
	if(sockfd < 0){
		perror("socket error");
		exit(1);
	}

	struct sockaddr_in serveraddr;
	memset(&serveraddr,0,sizeof(serveraddr));
	serveraddr.sin_family = AF_INET;
	serveraddr.sin_port = htons(atoi(argv[1]));
	serveraddr.sin_addr.s_addr = INADDR_ANY;
	if(bind(sockfd,(struct sockaddr*)&serveraddr,
				sizeof(serveraddr)) < 0){
		perror("bind error");
		exit(1);
	}

	char buffer[1024];
	struct sockaddr_in clientaddr;
	socklen_t len = sizeof(clientaddr);
	while(1){
		memset(buffer,0,sizeof(buffer));
		memset(&clientaddr,0,sizeof(clientaddr));
		if(recvfrom(sockfd,buffer,sizeof(buffer),0,
			(struct sockaddr*)&clientaddr,&len) < 0){
			perror("recvfrom error");
			exit(1);
		}
		else{
			char ip[16];
			inet_ntop(AF_INET,&clientaddr.sin_addr.s_addr,
					ip,sizeof(ip));
			int port = ntohs(clientaddr.sin_port);
			printf("%s(%d):%s\n",ip,port,buffer);
		}
	}
	return 0;
}

3.2 broadcasting transmitter

#include<netdb.h>
#include<sys/socket.h>
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<arpa/inet.h>

int main(int argc,char *argv[]){
	if(argc < 3){
		fprintf(stderr,"usage: %s ip port\n",argv[0]);
		exit(1);
	}
	
	int sockfd = socket(AF_INET,SOCK_DGRAM,0);
	if(sockfd < 0){
		perror("socket error");
		exit(1);
	}
	int opt = 1;
	//Broadcast
	setsockopt(sockfd,SOL_SOCKET,
			SO_BROADCAST,&opt,sizeof(opt));

	struct sockaddr_in serveraddr;
	memset(&serveraddr,0,sizeof(serveraddr));
	serveraddr.sin_family = AF_INET;
	serveraddr.sin_port = htons(atoi(argv[2]));
	inet_pton(AF_INET,argv[1],
			&serveraddr.sin_addr.s_addr);
	printf("I will broadcast...\n");
	char *info = "hello llc";
	size_t size = strlen(info) * sizeof(char);
	if(sendto(sockfd,info,size,0,
			(struct sockaddr*)&serveraddr,
				sizeof(serveraddr)) < 0){
		perror("sento error");
		exit(1);
	}
	else{
		printf("broadcast success\n");
	}

	return 0;
}

3.3 operation results

The following are all tested locally:
1. Start the receiving client:

2 start the sender connection, and the receiver receives the connection from the client:

The return message indicates whether the socket can be monitored (getsockopt only)

86 original articles published, praised 7, visited 1004
Private letter follow

Tags: socket network

Posted on Thu, 16 Jan 2020 08:52:30 -0800 by derrick24