MST

星途 面试题库

面试题:C语言实现Linux下简单Web服务器的请求解析

在Linux环境下,使用C语言编写一个函数,用于解析HTTP请求。假设HTTP请求格式为标准格式,函数需要提取出请求方法(如GET、POST)、请求路径等关键信息。要求代码清晰,能处理常见的HTTP请求格式错误。
26.7万 热度难度
编程语言C

知识考点

AI 面试

面试题答案

一键面试
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

#define MAX_REQUEST_LENGTH 1024

typedef struct {
    char method[10];
    char path[MAX_REQUEST_LENGTH];
} HttpRequest;

int parseHttpRequest(const char *request, HttpRequest *httpRequest) {
    const char *start = request;
    const char *end;

    // 提取请求方法
    end = strchr(start,'');
    if (end == NULL) {
        return -1; // 格式错误,没有找到请求方法后的空格
    }
    strncpy(httpRequest->method, start, end - start);
    httpRequest->method[end - start] = '\0';

    // 跳过空格
    start = end + 1;

    // 提取请求路径
    end = strchr(start,'');
    if (end == NULL) {
        return -2; // 格式错误,没有找到请求路径后的空格
    }
    strncpy(httpRequest->path, start, end - start);
    httpRequest->path[end - start] = '\0';

    return 0;
}

你可以使用以下方式调用这个函数:

int main() {
    char request[MAX_REQUEST_LENGTH] = "GET /index.html HTTP/1.1";
    HttpRequest httpRequest;
    int result = parseHttpRequest(request, &httpRequest);
    if (result == 0) {
        printf("Method: %s\n", httpRequest.method);
        printf("Path: %s\n", httpRequest.path);
    } else if (result == -1) {
        printf("HTTP request format error: cannot find space after method\n");
    } else if (result == -2) {
        printf("HTTP request format error: cannot find space after path\n");
    }
    return 0;
}