c语言实现http服务器 csdn
时间: 2023-11-17 09:03:19 浏览: 39
在C语言中实现一个简单的HTTP服务器可以使用开源的库,例如libmicrohttpd或mongoose。以下是使用libmicrohttpd库实现的示例代码:
```c
#include <microhttpd.h>
#include <stdio.h>
#include <string.h>
int answer_to_connection(void *cls,
struct MHD_Connection *connection,
const char *url,
const char *method,
const char *version,
const char *upload_data,
size_t *upload_data_size,
void **con_cls)
{
const char *page = "<html><body><h1>Hello, CSDN!</h1></body></html>";
struct MHD_Response *response;
int ret;
(void)cls; // 忽略传递的参数
if (0 != strcmp(method, "GET"))
return MHD_NO; // 仅处理GET请求
response = MHD_create_response_from_buffer(strlen(page), (void *)page, MHD_RESPMEM_PERSISTENT);
ret = MHD_queue_response(connection, MHD_HTTP_OK, response);
MHD_destroy_response(response);
return ret;
}
int main()
{
struct MHD_Daemon *daemon;
daemon = MHD_start_daemon(MHD_USE_THREAD_PER_CONNECTION, 8080, NULL, NULL,
&answer_to_connection, NULL, MHD_OPTION_END);
if (NULL == daemon)
return 1;
getchar();
MHD_stop_daemon(daemon);
return 0;
}
```
这段代码使用了libmicrohttpd库来创建一个HTTP服务器。它在8080端口上监听连接,并在收到GET请求时返回一个简单的HTML页面。你可以根据实际需要进行修改和扩展。
编译并运行这个程序后,你可以在浏览器中访问http://localhost:8080/来查看服务器的响应。输出的页面将包含一个标题为"Hello, CSDN!"的大标题。
请注意,这只是一个简单的示例,实际上,编写一个完整的HTTP服务器可能需要更多的代码,包括处理不同的HTTP方法,处理请求参数、存储和访问数据等。