Reaves.dev

v0.1.0

built using

Phoenix v1.7.12

Parse Http Body

Stephen M. Reaves

::

2022-08-06

How to parse http body in C

Snippet

#define BUFFER_SIZE 1024

void parseBody(char *buffer) {
    char *delim = \r\n\r\n;
    char *bodyStart = strstr(buffer, delim);
    long delimLocation = bodyStart - buffer;
    char *body = malloc(strlen(buffer));

    strncopy(body, buffer + delimLocation + strlen(delim), strlen(buffer) - delimLocation);

    printf(Body is %s\n, body);

    free(body);
}

// This part of thie code is mostly from
// https://bruinsslot.jp/post/simple-http-webserver-in-c/
void readBody(struct sockaddr_in host_addr) {
    char buffer[BUFFER_SIZE], method[BUFFER_SIZE], uri[BUFFER_SIZE], version[BUFFER_SIZE], body[BUFFER_SIZE];

    int host_addr_len = sizeof(host_addr);
    int newsockfd = accept(sockfd, (struct sockaddr *)&host_addr,
                           (socklen_t *)&host_addr_len);

    if (newsockfd < 0) {
        perror(Error accepting connection);
        return;
    }

    // Read from Socket
    int valread = read(newsockfd, buffer, BUFFER_SIZE);
    if (valread < 0) {
        perror(Error reading from socket);
        return;
    }

    sscanf(buffer, %s %s %s, method, uri, version);

    parseBody(buffer);
}