Introduction to the process of creating TCP connection in Linux system

Introduction to the process of creating TCP connection in Linux system

Steps to create TCP in Linux

TCP programming requires two sets of codes for the client and server, and the process of creating TCP is not completely consistent.

Server

Create a socket using the socket function

Use the setsockopt function to set the socket properties

Use the bind function to bind the IP address and port information to the socket and use the listen function to listen to the specified port

Use the accept function to receive the client's connection request

Use send/recv and read/write functions to send and receive data

Use the close function to close the network connection and monitor

Client

Use the socket function to create a socket and use the setsockopt function to set socket properties

Use the bind function to bind the IP address and port information

Set the IP address and port to connect to and use the connect function to request a connection

Use send/recv and read/write functions to send and receive data

Use the close function to close the network connection

TCP establishment process

Linux creates TCP connection process_linux

Sample Code

server

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <fcntl.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <pthread.h>
#include <time.h>
#define MAXSIZE 128

char news[MAXSIZE];
int res; //Used to receive function return value void* pthread_chat(void * arg) //Create a thread to receive data {
    int confd = *(int *)arg;
    while(1)
    {
        res = recv(confd, news, sizeof(news), 0);
        if(res <= 0)
        {
        perror("recv");
        break;
        }
        printf("The news is: %s\n",news);
        memset(news,0,MAXSIZE);
        send(confd,"OK",2,0);
    }

    printf("One client over\n");
    close(confd);
}

char *Time() //Get the current time {
    time_t timer;
    struct tm *tblock;
    timer = time(NULL);
    tblock = localtime(&timer);
    return asctime(tblock);
}

void save(char *s) //Store log file {
    int fd;
    fd = open("journal",O_RDWR|O_APPEND|O_CREAT);

    if(fd < 0)
        perror("open");
    else
    {
        char *buf = Time();
        strcat(buf,s);

        write(fd,buf,MAXSIZE);
        lseek(fd,0,SEEK_END);

        if(res < 0)
            perror("write");
    }
}

int main()
{
    int sockfd = socket(AF_INET, SOCK_STREAM, 0);
    struct sockaddr_in saddr, caddr;
    saddr.sin_family = AF_INET;
    saddr.sin_port = htons(6666);
    saddr.sin_addr.s_addr = inet_addr("127.0.0.1");

    res = bind(sockfd,(struct sockaddr*)&saddr,sizeof(saddr));
    if(res < 0)
        perror("bind");

    listen(sockfd, 5); //Listen to port while(1)
    {
        int len ​​= sizeof(caddr);
        int confd = accept(sockfd,(struct sockaddr*)&caddr, &len);
        if(confd < 0)
        {
            perror("accept");
            continue;
        }else
        {
            save(inet_ntoa(caddr.sin_addr));
        }

        printf("Accept confdis:%d, ip=%s\n",confd,inet_ntoa(caddr.sin_addr));

        pthread_t tid;
        pthread_create(&tid, NULL, pthread_chat, &confd);
    }
}

Client

#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>  
#define MAXSIZE 128

char news[MAXSIZE];
int res; //Used to receive function return value int main()
{
    printf("------Welcome join the chat room-----\n");
    printf("If you want to quit,please input --bye--\n");
    int sockfd = socket(AF_INET, SOCK_STREAM, 0);

    struct sockaddr_in saddr;
    saddr.sin_family = AF_INET;
    saddr.sin_port = htons(6666);
    saddr.sin_addr.s_addr = inet_addr("127.0.0.1");

    int confd = connect(sockfd,(struct sockaddr*)&saddr,sizeof(saddr));
    if(confd < 0)
        perror("connect");

    while(1)
    {
        printf("Please input the news\n");
        fgets(news,MAXSIZE,stdin);

        if(strncmp(news,"bye",3) == 0)
        {
            break;
        }

        send(sockfd, news, strlen(news), 0);
        memset(news,0,MAXSIZE);
        recv(sockfd, news, sizeof(news), 0);
          printf("The serve's news is: %s\n",news);
    }

    close(sockfd);
    exit(0);
}

Please note that since the server uses multi-threaded development, you need to add the -lpthread option when compiling.

The program running effect is as follows:

Linux creates TCP connection process_network communication_02

This is the end of this article about the process of creating TCP connection in Linux system. For more relevant content about creating TCP connection in Linux, please search previous articles on 123WORDPRESS.COM or continue to browse the related articles below. I hope you will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • How to test the maximum number of TCP connections in Linux
  • Solution to TCP connection timeout problem on Linux
  • 2 commands to check TCP connection under Linux

<<:  14 practical experiences on reducing SCSS style code by 50%

>>:  Call the font according to the font name to let the browser display the font you want

Recommend

Solution to the problem that Docker container cannot access Jupyter

In this project, the Docker container is used to ...

Vue-pdf implements online preview of PDF files

Preface In most projects, you will encounter onli...

JavaScript array deduplication solution

Table of contents Method 1: set: It is not a data...

Sample code for implementing horizontal infinite scrolling with pure CSS3

The examples in this article are all written in s...

Design theory: the basics of font design

<br />Words are the inevitable product of hu...

A brief discussion on HTML doctype and encoding

DOCTYPE Doctype is used to tell the browser which...

How to reduce the memory and CPU usage of web pages

<br />Some web pages may not look large but ...

js to implement verification code interference (dynamic)

This article example shares the specific code of ...

Example analysis of the usage of the new json field type in mysql5.7

This article uses an example to illustrate the us...

How to migrate the data directory in Docker

Table of contents View Disk Usage Disk Cleanup (D...

MySQL table addition, deletion, modification and query basic tutorial

1. Create insert into [table name] (field1, field...

Using NTP for Time Synchronization in Ubuntu

NTP is a TCP/IP protocol for synchronizing time o...

CSS naming conventions (rules) worth collecting Commonly used CSS naming rules

CSS naming conventions (rules) Commonly used CSS ...