基于上一篇中 网络编程基础:TCP/UDP 协议 实现了基于 TCP 协议的网络通信模型。基于此之上,我们继续介绍 加密传输、用多线程实现客户端程序与网络调试助手进行双向通信(多线程并发服务器)。
这是一个基于 OpenSSL 的 TLS(SSL)加密传输的 TCP 服务器-客户端 通信示例。这种方式可以确保数据在传输过程中被加密,防止中间人攻击和数据窃取。
代码说明
使用 OpenSSL:提供TLS/SSL加密通信。
服务器(server.c):
- 生成 TLS 证书并加载;
- 监听客户端连接;
- 通过 TLS 进行加密通信。
客户端(client.c):连接服务器并使用 TLS 进行加密通信。
生成 SSL 证书(自签名)
在运行代码之前,我们需要生成自签名证书:
openssl req -x509 -newkey rsa:2048 -keyout key.pem -out cert.pem -days 365 -nodes
执行后会要求输入一些信息(可以随意填写),这样会生成:
cert.pem
(SSL 证书)key.pem
(私钥)
服务器代码(server.c)
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <openssl/ssl.h>
#include <openssl/err.h>#define PORT 8080
#define BUFFER_SIZE 1024void init_openssl() {SSL_library_init();OpenSSL_add_all_algorithms();SSL_load_error_strings();
}SSL_CTX *create_context() {const SSL_METHOD *method = SSLv23_server_method();SSL_CTX *ctx = SSL_CTX_new(method);if (!ctx) {perror("Unable to create SSL context");ERR_print_errors_fp(stderr);exit(EXIT_FAILURE);}return ctx;
}void configure_context(SSL_CTX *ctx) {if (SSL_CTX_use_certificate_file(ctx, "cert.pem", SSL_FILETYPE_PEM) <= 0 ||SSL_CTX_use_PrivateKey_file(ctx, "key.pem", SSL_FILETYPE_PEM) <= 0) {ERR_print_errors_fp(stderr);exit(EXIT_FAILURE);}
}int main() {int server_fd, client_fd;struct sockaddr_in address;socklen_t addr_len = sizeof(address);char buffer[BUFFER_SIZE] = {0};init_openssl();SSL_CTX *ctx = create_context();configure_context(ctx);server_fd = socket(AF_INET, SOCK_STREAM, 0);if (server_fd < 0) {perror("Socket creation failed");exit(EXIT_FAILURE);}address.sin_family = AF_INET;address.sin_addr.s_addr = INADDR_ANY;address.sin_port = htons(PORT)