linux c 写一个tcp服务端代码,监听13400端口
时间: 2024-01-21 16:17:58 浏览: 179
以下是一个简单的C语言TCP服务端代码,可以监听13400端口:
```c
#include <stdio.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <string.h>
int main() {
int server_socket, client_socket;
struct sockaddr_in server_address, client_address;
char buffer[1024];
// 创建socket
server_socket = socket(AF_INET, SOCK_STREAM, 0);
if (server_socket == -1) {
printf("Error: Failed to create socket.\n");
exit(1);
}
// 设置server_address
server_address.sin_family = AF_INET;
server_address.sin_addr.s_addr = INADDR_ANY;
server_address.sin_port = htons(13400);
// 绑定socket
if (bind(server_socket, (struct sockaddr*) &server_address, sizeof(server_address)) == -1) {
printf("Error: Failed to bind.\n");
exit(2);
}
// 监听socket
if (listen(server_socket, 5) == -1) {
printf("Error: Failed to listen.\n");
exit(3);
}
printf("Server is listening on port 13400...\n");
// 接受客户端连接
socklen_t client_address_size = sizeof(client_address);
client_socket = accept(server_socket, (struct sockaddr*) &client_address, &client_address_size);
if (client_socket == -1) {
printf("Error: Failed to accept connection.\n");
exit(4);
}
printf("Client connected.\n");
// 从客户端接收数据并回复
while (1) {
memset(buffer, 0, sizeof(buffer));
int bytes_received = recv(client_socket, buffer, sizeof(buffer), 0);
if (bytes_received == -1) {
printf("Error: Failed to receive data.\n");
exit(5);
} else if (bytes_received == 0) {
printf("Client disconnected.\n");
break;
}
printf("Received: %s\n", buffer);
int bytes_sent = send(client_socket, buffer, strlen(buffer), 0);
if (bytes_sent == -1) {
printf("Error: Failed to send data.\n");
exit(6);
}
}
// 关闭sockets
close(client_socket);
close(server_socket);
return 0;
}
```
这段代码创建一个TCP socket,然后绑定到13400端口上,通过listen函数开始监听。当客户端连接时,accept函数会返回客户端的socket,然后服务端就可以开始和客户端通信了。在这个例子中,服务端会接收客户端发来的消息,并将消息原封不动地回复给客户端。关闭连接时,需要关闭两个socket:客户端socket和服务端socket。
阅读全文