C language rehabilitation record II: TCP/IP protocol cluster

TCP/IP protocol cluster

When network programming, we will inevitably encounter the problem of communication protocol
The full name of TCP/IP protocol cluster is called transmission control protocol/Internet protocol, that is, transmission control protocol and Ethernet interconnection protocol. All network protocols are in this protocol cluster, including TCP protocol, UDP protocol, IP protocol, IMCP protocol, HTTP protocol, etc TCP/IP protocol cluster is the most basic standard of network communication
TCP/IP protocol cluster is generally divided into four layers: application layer, transport layer, network layer and network interface layer

Application layer

It includes all high-level protocols, such as TELNET,FTP,SMTP,DNS,NNTP,HTTP,MQTT, etc. the application layer has agreed on the specific communication format

Transport layer

It includes TCP protocol and UDP protocol. The function of the transport layer is to distribute the packets sealed by the application layer to the next layer according to the address in the packet. TCP protocol is a connection oriented protocol, while UDP is a connectionless protocol

Internet layer

IP protocol is commonly used. Its function is to group the packets with sealed addresses, and then send them to the next layer

Network interface layer

The basic part of network communication is responsible for sending and receiving ip packets. It is the actual connection layer between PC and network

The application layer is equivalent to processing the content of the letter, the transport layer is responsible for the address of the letter, the network layer plans the transportation route, and the network interface layer is the logistics turnover center

In network communication, a message becomes a packet. Take TCP protocol as an example:

Hierarchical structure14 bytes20 bytes20 bytes4 bytes
application layeruser data
Transport layerTCP headeruser data
network layerIP headerTCP headeruser data
Network interface layerNetwork headerIP headerTCP headeruser dataEthernet tail

After the user data passes through all levels, it is encapsulated into data packets and transmitted in the network. After receiving the data packets, it is unpacked layer by layer to obtain the final user data

communication protocol

The scope of communication protocol is vague, divided by function and process

TCP protocol

TCP protocol is a connection oriented and highly reliable protocol acting on the transport layer. The message format of TCP is as follows:

namedigit
Source port number16 bit
Destination port number16 bit
serial number32 bit
Confirmation number32 bit
TCP header length4 bit
Reserved bit6 bit
Window size16 bit
Checksum16 bit
Emergency pointer16 bit
optionreserved
user datareserved

UDP protocol

UDP protocol is an unreliable protocol for connectionless at the transport layer. The message format is as follows:

namedigit
Source port number16 bit
Destination port number16bit
User packet length16 bit
Inspection and16 bit
data

TCP and UDP comparison

connectivity

TCP is a highly reliable connection oriented protocol. Three handshakes are required for establishing a connection between the client and the server, and four handshakes are required for disconnecting the connection

UDP is a connectionless real-time protocol. UDP protocol does not have a client or server in essence, and there is no need to establish a connection. UDP only sends the data flow to a certain area, and all devices in the area can receive the data

reliability

TCP protocol has process control. The packet will be marked in the process of subcontracting, and there will be no situation of last mover first mover
UDP protocol is designed to do its best to transmit data, regardless of whether the data receiver is accurate or not

Message header

Because of the reliability design of TCP protocol, there are relatively many message headers
Due to the design of data delivery first, UDP protocol has only necessary data in the header of the message, which is relatively simplified

Duplex

TCP protocol can only carry out point-to-point high reliability full duplex communication
UDP protocol can carry out one to many, one to one, many to one and many to many communication

Application scenario

TCP protocol

Because of its high reliability, TCP protocol is generally used in file transmission, web page or communication software

UDP protocol

Due to its real-time, duplex and low performance overhead, UDP protocol is generally used in LAN device discovery, video live broadcast and other scenarios

Related code

Because there are few complete codes used in the project, if you have time to supplement them later
send

#include <stdio.h>  
#include <stdlib.h>  
#include <unistd.h>  
#include <fcntl.h>  
#include <sys/socket.h>  
#include <netinet/in.h>  
#include <arpa/inet.h>  
#include <string.h>  
#include <errno.h>  
#include <sys/types.h>  

#define PORT	1617

int get_local_ip(char * ifname, char * ip)
{
    char *temp = NULL;
    int inet_sock;
    struct ifreq ifr;

    inet_sock = socket(AF_INET, SOCK_DGRAM, 0); 

    memset(ifr.ifr_name, 0, sizeof(ifr.ifr_name));
    memcpy(ifr.ifr_name, ifname, strlen(ifname));

    if(0 != ioctl(inet_sock, SIOCGIFADDR, &ifr)) 
    {   
        perror("ioctl error");
        return -1;
    }

    temp = inet_ntoa(((struct sockaddr_in*)&(ifr.ifr_addr))->sin_addr);     
    memcpy(ip, temp, strlen(temp));

    close(inet_sock);

    return 0;
}


int main()
{
	setvbuf(stdout,NULL,_IONBF,0);
	fflush(stdout);
	
	int sd=-1;
	if((sd = socket(AF_INET,SOCK_DGRAM,0)) == -1)
	{
		printf("socket error\n");
		return -1;
	}
	const int opt=1;
	int nb=0;
	nb = setsockopt(sd,SOL_SOCKET,SO_BROADCAST,(char *)&opt,sizeof(opt));
	if(nb == -1)
	{
		printf("set socket error\n");
		return -1;
	}

	struct sockaddr_in addr_to;
	bzero(&addr_to,sizeof(struct sockaddr_in));
	addr_to.sin_family=AF_INET;
	addr_to.sin_addr.s_addr=htonl(INADDR_BROADCAST);
	addr_to.sin_port=htons(PORT);
	int nlen=sizeof(addr_to);

	while(1)
	{
		sleep(1);
		char smsg[]={"I AM HERE\n"};
		int ret=sendto(sd,smsg,strlen(smsg),0,(struct sockaddr*)&addr_to,nlen);
		if(ret<0)
		{
			printf("send error\n");
		}
		else
		{
			printf("ok\n");
		}
	}

}

rec

#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
  
#define PORT 1617

int main()  
{  
    setvbuf(stdout, NULL, _IONBF, 0);   
    fflush(stdout);   
  

    struct sockaddr_in addrto;  
    bzero(&addrto, sizeof(struct sockaddr_in));  
    addrto.sin_family = AF_INET;  
    addrto.sin_addr.s_addr = htonl(INADDR_ANY);  
    addrto.sin_port = htons(PORT);  
      
  
    struct sockaddr_in from;  
    bzero(&from, sizeof(struct sockaddr_in));  
    from.sin_family = AF_INET;  
    from.sin_addr.s_addr = htonl(INADDR_ANY);  
    from.sin_port = htons(PORT);  
      
    int sock = -1;  
    if ((sock = socket(AF_INET, SOCK_DGRAM, 0)) == -1)   
    {     
        printf("socket error\n");   
        return -1;  
    }     
  
    const int opt = 1;  
 
    int nb = 0;  
    nb = setsockopt(sock, SOL_SOCKET, SO_BROADCAST, (char *)&opt, sizeof(opt));  
    if(nb == -1)  
    {  
        printf("set socket error...\n");  
        return -1;  
    }  
  
    if(bind(sock,(struct sockaddr *)&(addrto), sizeof(struct sockaddr_in)) == -1)   
    {     
        printf("bind error...\n");  
        return -1;  
    }  
  
    int len = sizeof(struct sockaddr_in);  
    char smsg[100] = {0};  
  
    while(1)  
    {  
 
        int ret=recvfrom(sock, smsg, 100, 0, (struct sockaddr*)&from,(socklen_t*)&len);  
        if(ret<=0)  
        {  
            printf("read error....\n");  
        }  
        else  
        {         
            printf("%s\t", smsg);     
        }  
  
        sleep(1);  
    }  
  
    return 0;  
}  

Keywords: C

Added by XTTX on Sun, 23 Jan 2022 03:57:54 +0200