linux network notes

Overview of network programming

1, Differences between TCP and UDP protocols:

Understand the difference between TCP and UDP - Fundebug - blog Garden

2, TCP/UDP comparison:

1. TCP is connection oriented (for example, dial up to establish a connection before making a call). UDP is connectionless, that is, it is not necessary to establish a connection before sending data

two   TCP provides reliable services. That is, the data transmitted through TCP connection is error free, not lost, not repeated, and arrives in sequence; UDP tries its best to deliver, that is, reliable delivery is not guaranteed

three   TCP is byte stream oriented. In fact, TCP regards data as a series of unstructured byte streams; UDP is message oriented. UDP has no congestion control, so network congestion will not reduce the transmission rate of the source host (very useful for real-time applications, such as IP telephony, real-time video conference, etc.)

four   Each TCP connection can only be point-to-point; UDP supports one-to-one, one to many, many to one and many to many interactive communication

five   TCP header overhead is 20 bytes; UDP header overhead is small, only 8 bytes

six   The logical communication channel of TCP is full duplex reliable channel, while UDP is unreliable channel

3, Port number function:

A host with an IP address can provide many services, such as Web services, FTP services, SMTP services, etc

These services can be realized through one IP address. Then, how does the host distinguish different network services? Obviously, it can't rely only on IP addresses, because the relationship between IP addresses and network services is one to many.

In fact, different services are distinguished by "IP address + port number".

Port provides an access channel.

Servers are generally identified by well-known port numbers. For example, for each TCP/IP implementation, the TCP port number of FTP server is 21, the TCP port number of each Telnet server is 23, and the UDP port number of each TFTP (simple file transfer protocol) server is 69

4, Byte order

1, Byte order: refers to multi byte data in Computer memory The storage order of each byte during storage in or network transmission.

1. Little endian: store low order bytes at the starting address

2. Big endian: store high-order bytes at the starting address

Network byte order = large end byte order.

X86 CPUs are   Little endian

2, Byte order conversion api:

#include <netinet/in.h>

uint16_t htons(uint16_t host16bitvalue);    // Returns the value of the network byte order

uint32_t htonl(uint32_t host32bitvalue);    // Returns the value of the network byte order

uint16_t ntohs(uint16_t net16bitvalue);     // Returns the value of the host byte order

uint32_t ntohl(uint32_t net32bitvalue);     // Returns the value of the host byte order

h stands for host, n for net, s for short (two bytes), and l for long (four bytes). The conversion between host byte order and network byte order can be realized through the above four functions. Sometimes, the address can be specified by INADDR_ANY and INADDR_ANY to be obtained by the operating system itself

3, Address translation API

int inet_aton(const char* straddr,struct in_addr *addrp);

Convert "192.168.1.123" in the form of string to a format recognized by the network

char* inet_ntoa(struct in_addr inaddr); convert the ip address in network format to string form

---------------------------------------------------------------------------------------------------------------------------

Example: storage method of double word 0x01020304(DWORD) in memory

Memory address

4000&4001&4002&4003

LE 04 03 02 01

BE 01 02 03 04

Development steps and code implementation of Socket server and client

The so-called socket is the abstraction of the endpoint for two-way communication between application processes on different hosts in the network.

A socket is the end of process communication on the network, which provides a mechanism for application layer processes to exchange data using network protocol.

In terms of its position, the socket connects the application process and the network protocol stack. It is the interface for the application to communicate through the network protocol and the interface for the application to interact with the network protocol root

1, Development steps:

① Create socket

② Add information (IP address and port number) to the socket

    1. Pay attention to the byte order of port number 2. Pay attention to converting the digital IP address string into a network recognizable format

③ Monitor network connections

④ Listen for client access and accept a connection

⑤ Data interaction

⑥ Close the socket and disconnect

                                                  (development steps of Sockt server and client)

2, Functions and parameters of each step:

① Create socket

int socket(int domain, int type, int protocol);

  ② Add information (IP address and port number) to the socket

int bind(int sockfd,const struct sockaddr *addr,socklen_t addrlen);.

First parameter socket return character

The second structure contains the type + ip + termination slogan

The third parameter is the structure size

 

 

eg: about searching structure in / usr/include /

①struct sockaddr_in     This structure can be searched under cd /usr/include /

grep "struct sockaddr_in {" * -nir

Search for places defined by "struct sockaddr_in"  * In the current directory, nir means: display line numbers, case insensitive, recursive search

linux/in.h:184:struct sockaddr_in {       The header file is followed by the number of lines

vi linux/in.h +184 on

struct sockaddr_in {
  __kernel_sa_family_t  sin_family;     /* Address family               */
  __be16                sin_port;       /* Port number                  */
  struct in_addr        sin_addr;       /* Internet address             */

  /* Pad to size of `struct sockaddr'. */
  unsigned char         __pad[__SOCK_SIZE__ - sizeof(short int) -
                        sizeof(unsigned short int) - sizeof(struct in_addr)];
};
②struct in_addr   For the structure in the above structure, search in the same way to obtain the header file and structure

linux/in.h:56:struct in_addr {

vi linux/in.h +184 on

struct in_addr {
        __ be32   s_addr;//32-bit integer
};
 

③ listen(); listening function

int listen(int sockfd, int backlog);

Parameter 2: number of listeners

  ④ Connection: listen for client access and receive a connection

int accept(int sockfd, struct sockaddr *addr, socklen_t *addrlen);

The second parameter is the client   The third parameter is the client length

The return value of accept c_fd is a new socket. Connect the socket through s_fd to create a new socket to serve the client

  int c_fd = accept(); / / for subsequent operations on the client, use c_fd to operate (connect to the client through c_fd)

2, Server and client code sections

1. Server code (server side)

◆ use "ifconfig -a" to view the server (linux native) IP address

◆ ping is used to determine whether the local host can successfully exchange (send and receive) data packets with another host, and then it can be inferred from the returned information TCP/IP Whether the parameters are set correctly, whether the operation is normal, whether the network is unobstructed, etc.

#include<stdio.h>
#include <sys/types.h>          /* See NOTES */
#include <sys/socket.h>
//#include<linux/in.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include<stdlib.h>

int main(){
        int s_fd;

        //1.socket();

        s_fd = socket(AF_INET,SOCK_STREAM,0);
        if(s_fd == -1){
                perror("socket\n");
                exit-(1);
        }
        struct sockaddr_in s_addr;//The improved structure of "network format --- port number --- IP address" can be configured            
                                                                 stay/usr/include/see
        s_addr.sin_family = AF_INET;
        s_addr.sin_port = htons(8989);//Conversion function of port number byte order (converting host byte order to network byte order)
//      int inet_aton(const char* straddr,struct in_addr *addrp);
        inet_aton("192.168.1.9",&s_addr.sin_addr);
        //Use the aton function to convert string data into network data. You can view struct in_addr at / usr/include /

        //2.bind();
// int bind(int sockfd, const struct sockaddr *addr,socklen_t addrlen);
        bind(s_fd,(struct sockaddr*)&s_addr,sizeof (struct sockaddr_in));

        //3.listen();
        listen(s_fd,10);
        //4.accept();
        int c_fd = accept(s_fd,NULL,NULL);
        //5.read();

        //6.write();
        printf("connect\n");
        while(1);
        return 0;
}

2. socket client code (server)

After creating the server and client sockets, you need to clear the data with memset

#include<stdio.h>
#include <sys/types.h>          /* See NOTES */
#include <sys/socket.h>
//#include<linux/in.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include<stdlib.h>
#include<string.h>

int main(){

        int s_fd;
        int n_read;
        char readbuf[128];
        char *msg = "I get your msg";

        struct sockaddr_in s_addr;
        struct sockaddr_in c_addr;

        memset(&s_addr,0,sizeof(struct sockaddr_in));
        memset(&c_addr,0,sizeof(struct sockaddr_in));

        //1.socket();

        s_fd = socket(AF_INET,SOCK_STREAM,0);
        if(s_fd == -1){
                perror("socket\n");
                exit-(1);
        }

        s_addr.sin_family = AF_INET;
        s_addr.sin_port = htons(8888);
//      int inet_aton(const char* straddr,struct in_addr *addrp);
        inet_aton("192.168.1.9",&s_addr.sin_addr);

        //2.bind();
// int bind(int sockfd, const struct sockaddr *addr,socklen_t addrlen);
        bind(s_fd,(struct sockaddr *)&s_addr,sizeof (struct sockaddr_in));

        //3.listen();
        listen(s_fd,10);
        //4.accept();
        int c_len = sizeof(struct sockaddr_in);

        int c_fd = accept(s_fd,(struct sockaddr *)&c_addr,&c_len);
                    //It is mainly written for this. Note that the length is a pointer
        if(c_fd == -1){
                perror("c_fd accept defeat\n");
        }else{
                printf("client connect success%s\n",inet_ntoa(c_addr.sin_addr));
                                            //Output the client address and convert the network byte order
        }
        //5.read();
        n_read = read(c_fd,readbuf,128);
        if(n_read == -1){
                perror("read\n");
        }else{
                printf("get message:%d,%s\n",n_read,readbuf);
        }
        //6.write();
        write(c_fd,msg,strlen(msg));      //Return value

        return 0;
}

3, Client code

Realize the communication between client and server

#include<stdio.h>
#include <sys/types.h>          /* See NOTES */
#include <sys/socket.h>
//#include<linux/in.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include<stdlib.h>
#include<string.h>

int main(){

        int c_fd;
        int n_read;
        char readbuf[128];
        char *msg = "msg from client\n";

        struct sockaddr_in c_addr;
        memset(&c_addr,0,sizeof(struct sockaddr_in));

        //1.socket;
        c_fd = socket(AF_INET,SOCK_STREAM,0);
        if(c_fd == -1){
                perror("socket\n");
                exit-(1);
        }
       
        c_addr.sin_family = AF_INET;
        c_addr.sin_port = htons(8888);
/int inet_aton(const char* straddr,struct in_addr *addrp);
        inet_aton("192.168.1.9",&c_addr.sin_addr);

        //2.connect
        if(connect(c_fd,(struct sockaddr *)&c_addr,sizeof(struct sockaddr)) == -1){
                perror("connect");
                exit(-1);
        }else{
                printf("connect success\n");
        }

        //3.write;
        write(c_fd,msg,strlen(msg));
        //4.read
        n_read = read(c_fd,readbuf,128);
        if(n_read == -1){
                perror("read");
                exit(-1);
        }else{
                printf("get msg from servier\n");
        }

        return 0;
   }

Tags: Linux udp TCP/IP

Posted on Sat, 30 Oct 2021 01:04:03 -0400 by rj2kix