用Linux写一个服务端的C语言程序
时间: 2023-11-17 10:07:26 浏览: 89
以下是一个简单的Linux服务端C语言程序:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <unistd.h>
#define PORT 8000
#define MAX_BUFFER_SIZE 1024
int main() {
int server_fd, client_fd;
struct sockaddr_in server_addr, client_addr;
socklen_t client_addr_len;
char buffer[MAX_BUFFER_SIZE] = {0};
int bytes_received;
// 创建套接字
if ((server_fd = socket(AF_INET, SOCK_STREAM, 0)) == 0) {
perror("socket failed");
exit(EXIT_FAILURE);
}
// 设置服务器地址和端口
server_addr.sin_family = AF_INET;
server_addr.sin_addr.s_addr = INADDR_ANY;
server_addr.sin_port = htons(PORT);
// 绑定套接字到服务器地址和端口
if (bind(server_fd, (struct sockaddr *)&server_addr, sizeof(server_addr)) < 0) {
perror("bind failed");
exit(EXIT_FAILURE);
}
// 监听套接字
if (listen(server_fd, 5) < 0) {
perror("listen failed");
exit(EXIT_FAILURE);
}
printf("Server listening on port %d...\n", PORT);
while (1) {
// 接受客户端连接
client_addr_len = sizeof(client_addr);
if ((client_fd = accept(server_fd, (struct sockaddr *)&client_addr, &client_addr_len)) < 0) {
perror("accept failed");
exit(EXIT_FAILURE);
}
printf("Client connected from %s:%d\n", inet_ntoa(client_addr.sin_addr), ntohs(client_addr.sin_port));
// 接收数据
bytes_received = read(client_fd, buffer, MAX_BUFFER_SIZE);
if (bytes_received < 0) {
perror("read failed");
exit(EXIT_FAILURE);
}
printf("Received %d bytes from client:\n%s\n", bytes_received, buffer);
// 发送数据
if (write(client_fd, buffer, strlen(buffer)) < 0) {
perror("write failed");
exit(EXIT_FAILURE);
}
// 关闭客户端连接
close(client_fd);
}
return 0;
}
```
该程序使用TCP协议创建一个服务器,监听8000端口。当客户端连接成功后,服务器接收客户端发送的数据,然后再将数据返回给客户端。程序会一直运行,直到手动结束。
要编译该程序,可以使用以下命令:
```
gcc server.c -o server
```
然后使用./server命令运行程序即可。
阅读全文