在C语言中进行HTTP编程,通常有两种方法:
使用原生的socket编程
创建一个TCP监听socket,等待客户端连接。
解析请求,并生成HTTP响应数据。
将响应发送回客户端。
```c
include include include include include include define PORT 8080 define BUFFER_SIZE 1024 int main() { int server_fd, client_fd, addr_len; struct sockaddr_in server_addr, client_addr; char buffer[BUFFER_SIZE]; // 创建套接字 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, 3) < 0) { perror("listen"); exit(EXIT_FAILURE); } addr_len = sizeof(client_addr); // 接受客户端连接 if ((client_fd = accept(server_fd, (struct sockaddr *)&client_addr, (socklen_t *)&addr_len)) < 0) { perror("accept"); exit(EXIT_FAILURE); } // 读取并打印客户端请求 read(client_fd, buffer, BUFFER_SIZE); printf("Client request: %s\n", buffer); // 构造HTTP响应 char response[] = "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\nHello, World!