C language network programming (2)-TCP communication

C language network programming (2)-TCP communication

1. TCP client

1. Establish the connection
We want to use the socket, first of all, we first add the header file to be used

#include <stdio.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <arpa/inet.h>
#include <unistd.h>

Create a tcp socket, ipv4 protocol, use SOCK_STREAM parameter, protocol is 0, it will automatically select the tcp protocol by default;

    // 1、使用socket()函数获取一个socket文件描述符
	int tcp_client = socket(AF_INET, SOCK_STREAM, 0);

Then we put the server's IP address and port number in a structure to prepare

    // 2、准备服务端的地址和端口,'192.168.0.107'表示目的ip地址,12341表示目的端口号
    struct sockaddr_in server_addr = {0};	
	server_addr.sin_family = AF_INET;                           // 设置地址族为IPv4
	server_addr.sin_port = htons(12341);						// 设置地址的端口号信息
	server_addr.sin_addr.s_addr = inet_addr("192.168.0.107");	// 设置IP地址

Then use the connect method to connect, if the connection is successful, it returns 0. Failure returns -1

    // 3、链接到服务器
    ret = connect(tcp_client, (const struct sockaddr *)&server_addr, sizeof(server_addr));
    if (ret < 0)
		perror("connect");
    else
	    printf("connect result, ret = %d.\n", ret);

Finally, remember to close the socket

    // 4、关闭套接字
    close(tcp_client);

Compile and run, the connection is successful:
Insert picture description here
Insert picture description here
2, send data
Use send () function to send data

    // 4. 发送数据到服务端
	char sendbuf[]={"hello world."};
	ret = send(sockfd, sendbuf, strlen(sendbuf),0);

It can be seen that the data is successfully sent, the server has received the data
Insert picture description here
3.
If the data is to be received, then you can use the recv function to wait for the reception. Its parameter is the maximum number of bytes received, and then the received data is printed. come out
Insert picture description here
Insert picture description here

The complete code is as follows:

#include <stdio.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <arpa/inet.h>
#include <unistd.h>

int main(void)
{
    int ret;
    // 1、使用socket()函数获取一个TCP客户端socket文件描述符
	int tcp_client = socket(AF_INET, SOCK_STREAM, 0);
    if (-1 == tcp_client)
	{
		perror("socket");
		return -1;
	}

    // 2、准备服务端的地址和端口,'192.168.0.107'表示目的ip地址,12341表示目的端口号
    struct sockaddr_in server_addr = {0};	
	server_addr.sin_family = AF_INET;                           // 设置地址族为IPv4
	server_addr.sin_port = htons(12341);						// 设置地址的端口号信息
	server_addr.sin_addr.s_addr = inet_addr("192.168.0.107");	// 设置IP地址

    // 3、链接到服务器
    ret = connect(tcp_client, (const struct sockaddr *)&server_addr, sizeof(server_addr));
    if (ret < 0)
		perror("connect");
    else
	    printf("connect result, ret = %d.\n", ret);

    // 4. 发送数据到服务端
	char sendbuf[]={"hello world."};
	ret = send(tcp_client, sendbuf, strlen(sendbuf),0);

    // 5、等待接收服务端发送过来的数据,最大接收1024个字节
    char recvbuf[1024] = {0};
    ret = recv(tcp_client, recvbuf, sizeof(recvbuf), 0);

    // 6、将接收到的数据打印出来
    printf("Recvdate:%s \n",recvbuf);

    // 7、关闭套接字
    close(tcp_client);
}

Second, the TCP server

1. Establish the server and wait for the connection.
Similarly, we want to use the socket. First, we add the header file to be used.

#include <stdio.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <arpa/inet.h>
#include <unistd.h>

Create a tcp socket, ipv4 protocol, use SOCK_STREAM parameter, protocol is 0, it will automatically select the tcp protocol by default;

    // 1、使用socket()函数获取一个socket文件描述符
	int tcp_server = socket(AF_INET, SOCK_STREAM, 0);

In order for the client to connect to it, we need to bind a port number

    // 2. 绑定本地的相关信息,如果不绑定,则系统会随机分配一个端口号
    struct sockaddr_in local_addr = {0};
    local_addr.sin_family = AF_INET;		                    // 设置地址族为IPv4
	local_addr.sin_port = htons(8266);	                        // 设置地址的端口号信息
	local_addr.sin_addr.s_addr = inet_addr("192.168.0.107");	// 设置IP地址
	ret = bind(tcp_server, (const struct sockaddr *)&local_addr, sizeof(local_addr));
	if (ret < 0)
		perror("bind");
    else	
        printf("bind success.\n");

Then we can use the listen method to listen for connections. The second parameter is the number of queued connections we can wait for

    // 3、listen监听端口,阻塞,等待客户端来连接服务器
	ret = listen(sockfd, 5);

Use the accept method to wait for the client to connect to this server, the return value is the connected client socket file descriptor

    // 4、accept阻塞等待客户端接入
    struct sockaddr_in client_addr;
    socklen_t addrlen = sizeof(client_addr);
	int client_fd = accept(tcp_server, (struct sockaddr *)&client_addr, &addrlen);

We print out the client information linked to it

    // 5、打印连接过来的客户端信息及其ip地址
    printf("Client from %s:%d \n",inet_ntoa(*(struct in_addr*)&client_addr.sin_addr.s_addr),ntohs(client_addr.sin_port));

Then we can close the socket

     // 6、关闭套接字
    close(tcp_client);

Run the program and connect using the network debugging assistant. You can see that the connection is successful.
Insert picture description here
Insert picture description here
2. Receive data.
When a client connects, we can use the client socket file descriptor to wait for the data sent by the other party.

// 5、等待接收对方发送过来的数据
    char recvbuf[1024] = {0};
    ret = recv(client_fd, recvbuf, sizeof(recvbuf), 0);
    printf("Recv from %s:%d, ",inet_ntoa(*(struct in_addr*)&client_addr.sin_addr.s_addr),ntohs(client_addr.sin_port));
    printf("recv_data: %s \n",recvbuf);

Compile, run, and use the network debugging assistant client to send data. The results are as follows.
Insert picture description here
3. Send data After
receiving the data, we send the data back to tell the client that I have received the data

    // 6、返回数据到客户端
    char send_buf[1024] = "I have got the date:";
    strcat(send_buf,recvbuf);
    send(client_fd, send_buf, strlen(send_buf), 0);

Compile and run the result
Insert picture description here
Complete code

#include <stdio.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <arpa/inet.h>
#include <unistd.h>

int main(void)
{
    int ret = -1;
    // 1、使用socket()函数获取一个socket文件描述符
	int tcp_server = socket(AF_INET, SOCK_STREAM, 0);
    if (-1 == tcp_server)
	{
		perror("socket");
		return -1;
	}

    // 2. 绑定本地的相关信息,如果不绑定,则系统会随机分配一个端口号
    struct sockaddr_in local_addr = {0};
    local_addr.sin_family = AF_INET;		                    // 设置地址族为IPv4
	local_addr.sin_port = htons(8266);	                        // 设置地址的端口号信息
	local_addr.sin_addr.s_addr = inet_addr("192.168.0.107");	// 设置IP地址
	ret = bind(tcp_server, (const struct sockaddr *)&local_addr, sizeof(local_addr));
	if (ret < 0)
		perror("bind");
    else	
        printf("bind success.\n");

    // 3、listen监听端口,阻塞,等待客户端来连接服务器
	ret = listen(tcp_server, 5);

    // 4、accept阻塞等待客户端接入
    struct sockaddr_in client_addr;
    socklen_t addrlen = sizeof(client_addr);
	int client_fd = accept(tcp_server, (struct sockaddr *)&client_addr, &addrlen);

    // 5、等待接收对方发送过来的数据
    char recvbuf[1024] = {0};
    ret = recv(client_fd, recvbuf, sizeof(recvbuf), 0);
    printf("Recv from %s:%d, ",inet_ntoa(*(struct in_addr*)&client_addr.sin_addr.s_addr),ntohs(client_addr.sin_port));
    printf("recv_data: %s \n",recvbuf);

    // 6、返回数据到客户端
    char send_buf[1024] = "I have got the date:";
    strcat(send_buf,recvbuf);
    send(client_fd, send_buf, strlen(send_buf), 0);

     // 7、关闭套接字
    close(tcp_server);
}
Published 68 original articles · won 13 · views 5723

Guess you like

Origin blog.csdn.net/qq_38113006/article/details/105539262