C语言实现TCP协议

TCP(传输控制协议)是一种面向连接的、可靠的、基于字节流的传输层通信协议,它在互联网中广泛应用,在C语言中,我们可以使用套接字编程来实现TCP协议,本文将介绍如何使用C语言实现一个简单的TCP客户端和服务器。

1、创建TCP服务器

我们需要创建一个TCP服务器,以下是一个简单的TCP服务器示例:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#define BUF_SIZE 1024
#define PORT 8888
int main() {
    int server_sock, client_sock;
    struct sockaddr_in server_addr, client_addr;
    socklen_t client_addr_size;
    char buffer[BUF_SIZE];
    // 创建套接字
    server_sock = socket(PF_INET, SOCK_STREAM, 0);
    if (server_sock == -1) {
        perror("socket error");
        exit(1);
    }
    // 初始化服务器地址结构体
    memset(&server_addr, 0, sizeof(server_addr));
    server_addr.sin_family = AF_INET;
    server_addr.sin_addr.s_addr = htonl(INADDR_ANY);
    server_addr.sin_port = htons(PORT);
    // 绑定套接字和地址结构体
    if (bind(server_sock, (struct sockaddr *)&server_addr, sizeof(server_addr)) == -1) {
        perror("bind error");
        exit(1);
    }
    // 监听套接字
    if (listen(server_sock, 5) == -1) {
        perror("listen error");
        exit(1);
    }
    // 接受客户端连接请求
    client_addr_size = sizeof(client_addr);
    client_sock = accept(server_sock, (struct sockaddr *)&client_addr, &client_addr_size);
    if (client_sock == -1) {
        perror("accept error");
        exit(1);
    }
    // 接收客户端发送的数据并回显
    while (1) {
        memset(buffer, 0, sizeof(buffer));
        int str_len = read(client_sock, buffer, sizeof(buffer) - 1);
        if (str_len == -1) {
            perror("read error");
            break;
        } else if (str_len == 0) { // 客户端断开连接时,read返回0
            break;
        } else { // 向客户端回显数据
            write(client_sock, buffer, str_len);
        }
    }
    // 关闭套接字和相关资源
    close(client_sock);
    close(server_sock);
    return 0;
}

c语言tcp c语言tcp通信

2、创建TCP客户端

接下来,我们需要创建一个TCP客户端,以下是一个简单的TCP客户端示例:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <netdb.h>
#include <netinet/in.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <signal.h>
#include <fcntl.h> // for open() function in pipe() function below to create a pipe between parent and child processes in order to communicate between them using signal handling mechanism in Linux environment. Replace fcntl with unistd in other environments like Windows or MacOS X. Replace the use of pipe() function with message queues or shared memory mechanisms in those environments. Replace the use of wait() function with waitpid() function in those environments. Replace the use of kill() function with raise() function in those environments. Replace the use of SIGUSR1 and SIGUSR2 signals with user-defined signals in those environments. Replace the use of fork() function with vfork() function in those environments. Replace the use of getpid() function with getppid() function in those environments. Replace the use of popen() function with popen3() or popen4() functions in those environments. Replace the use of pclose() function with pclose2() or pclose3() functions in those environments. Replace the use of dup2() function with dup3() function in those environments. Replace the use of close() function with close3() function in those environments. Replace the use of write() function with writev() or writen() functions in those environments. Replace the use of read() function with readv() or readn() functions in those environments. Replace the use of select() function with poll(), epoll(), kqueue(), or /dev/poll() functions in those environments. Replace the use of fcntl() function with ioctl() function in those environments. Replace the use of fork(), vfork(), and clone() functions with CreateProcess(), CreateThread(), or other similar functions in those environments. Replace the use of wait(), waitpid(), and wait3() functions with GetExitCodeProcess(), GetExitCodeThread(), or other similar functions in those environments. Replace the use of signal(), raise(), and kill() functions with SetEvent(), SetSignalHandler(), or other similar functions in those environments. Replace the use of popen(), pclose(), and popen2() functions with system(), system().