请使用c语言写一个http服务器
时间: 2023-09-05 18:07:21 浏览: 78
c语言实现http服务器
4星 · 用户满意度95%
好的,以下是一个简单的C语言HTTP服务器的示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>
#define PORT 8080
#define BUFFER_SIZE 1024
int main(int argc, char const *argv[]) {
int server_fd, new_socket, valread;
struct sockaddr_in address;
int opt = 1;
int addrlen = sizeof(address);
char buffer[BUFFER_SIZE] = {0};
char *response = "HTTP/1.1 200 OK\nContent-Type: text/plain\nContent-Length: 12\n\nHello world!";
// Create socket file descriptor
if ((server_fd = socket(AF_INET, SOCK_STREAM, 0)) == 0) {
perror("socket failed");
exit(EXIT_FAILURE);
}
// Set socket options
if (setsockopt(server_fd, SOL_SOCKET, SO_REUSEADDR | SO_REUSEPORT, &opt, sizeof(opt))) {
perror("setsockopt failed");
exit(EXIT_FAILURE);
}
// Bind socket to port
address.sin_family = AF_INET;
address.sin_addr.s_addr = INADDR_ANY;
address.sin_port = htons(PORT);
if (bind(server_fd, (struct sockaddr *)&address, sizeof(address)) < 0) {
perror("bind failed");
exit(EXIT_FAILURE);
}
// Listen for incoming connections
if (listen(server_fd, 3) < 0) {
perror("listen failed");
exit(EXIT_FAILURE);
}
// Accept incoming connection
if ((new_socket = accept(server_fd, (struct sockaddr *)&address, (socklen_t*)&addrlen)) < 0) {
perror("accept failed");
exit(EXIT_FAILURE);
}
// Read incoming request
valread = read(new_socket, buffer, BUFFER_SIZE);
printf("%s\n", buffer);
// Send response
send(new_socket, response, strlen(response), 0);
printf("Hello message sent\n");
// Close sockets
close(new_socket);
close(server_fd);
return 0;
}
```
这个HTTP服务器使用了基本的套接字编程技术,监听端口8080,当有新的客户端连接时,读取客户端发送的请求,然后返回一个简单的响应消息。请注意,这个示例代码并不适用于生产环境,只是用于演示HTTP服务器的基本工作原理。
阅读全文