基于c语言的网络编程tcp透传,功能服务器能保存透传的信息记客户端的信息的代码
时间: 2024-10-23 11:15:15 浏览: 11
Linux下网络串口透传实现代码
3星 · 编辑精心推荐
在C语言中,基于TCP的网络编程通常会涉及到套接字编程(socket programming)。透传(Transparent Transfer)通常是指在网络通信中数据不做修改地从发送端直接传输到接收端。下面是一个简单的示例,展示了如何创建一个功能服务器,它接收客户端连接,并保存客户端信息及接收到的数据:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>
#define MAX_CLIENTS 5
#define BUFFER_SIZE 1024
struct client_info {
int socket;
char address[INET_ADDRSTRLEN];
};
void handle_client(int server_socket, struct sockaddr_in client_addr) {
char buffer[BUFFER_SIZE];
int bytes_received;
// 创建一个新的套接字用于与客户端通信
int client_socket = accept(server_socket, (struct sockaddr*)&client_addr, NULL);
if (client_socket == -1) {
perror("Error accepting connection");
return;
}
// 读取并保存客户端信息
bytes_received = recv(client_socket, buffer, sizeof(buffer), 0);
buffer[bytes_received] = '\0';
printf("Received from %s: %s\n", inet_ntoa(client_addr.sin_addr), buffer);
// 开始透传数据
while ((bytes_received = recv(client_socket, buffer, BUFFER_SIZE, 0)) > 0) {
send(client_socket, buffer, bytes_received, 0); // 直接转发给客户端
printf("Forwarded to client: %s\n", buffer);
}
if (bytes_received == 0) {
printf("Client closed the connection.\n");
} else {
perror("Error reading from client");
}
close(client_socket);
}
int main() {
int server_socket, port;
struct addrinfo hints, *res;
// 设置服务器地址和端口
memset(&hints, 0, sizeof(hints));
hints.ai_family = AF_UNSPEC; // 使用IPv4或IPv6
hints.ai_socktype = SOCK_STREAM; // TCP连接
hints.ai_flags = AI_PASSIVE; // 主动监听
if (getaddrinfo(NULL, "8080", &hints, &res) != 0) {
perror("Error getting address info");
exit(1);
}
server_socket = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
if (server_socket == -1) {
perror("Error creating socket");
freeaddrinfo(res);
exit(1);
}
if (bind(server_socket, res->ai_addr, res->ai_addrlen) == -1) {
perror("Error binding socket");
close(server_socket);
freeaddrinfo(res);
exit(1);
}
listen(server_socket, MAX_CLIENTS);
printf("Server listening on port %d...\n", ntohs(res->ai_port));
freeaddrinfo(res);
// 接受并处理客户端连接
while (true) {
struct sockaddr_in client_addr;
socklen_t client_len = sizeof(client_addr);
connfd = accept(server_socket, (struct sockaddr *)&client_addr, &client_len);
handle_client(connfd, client_addr);
}
close(server_socket);
return 0;
}
```
在这个示例中,服务器会在指定端口上监听连接请求,当有新客户端连接时,会创建一个新的套接字并与之通信。数据从客户端到达服务器后,服务器会简单地转发回去,实现了基本的TCP透传。
阅读全文