emptygif
Harshe: Hausa

Duk harsuna da frameworks

C with POSIX sockets (no dependencies) C

Snippet na C don C with POSIX sockets (no dependencies) da ke amsa requests zuwa /pixel.gif da empty GIF, wanda ake decoding ɗinsa sau ɗaya lokacin farawa.

C with POSIX sockets (no dependencies) C

Fayil
main.c
Gudanar
cc -O2 main.c -o pixel && ./pixel
/* A deliberately tiny, single-threaded HTTP/1.1 responder: one request per connection. */
#include <arpa/inet.h>
#include <netinet/in.h>
#include <stdio.h>
#include <string.h>
#include <sys/socket.h>
#include <unistd.h>

static const unsigned char GIF[] = {0x47, 0x49, 0x46, 0x38, 0x39, 0x61, 0x01, 0x00, 0x01, 0x00, 0x80, 0x00, 0x00, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x21, 0xf9, 0x04, 0x01, 0x00, 0x00, 0x00, 0x00, 0x2c, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x01, 0x00, 0x00, 0x02, 0x02, 0x44, 0x01, 0x00, 0x3b};

int main(void) {
    int srv = socket(AF_INET, SOCK_STREAM, 0);
    int on = 1;
    setsockopt(srv, SOL_SOCKET, SO_REUSEADDR, &on, sizeof on);
    struct sockaddr_in addr = {
        .sin_family = AF_INET,
        .sin_port = htons(8080),
        .sin_addr.s_addr = htonl(INADDR_ANY),
    };
    if (bind(srv, (struct sockaddr *) &addr, sizeof addr) < 0 || listen(srv, 64) < 0) {
        perror("bind/listen");
        return 1;
    }

    const char *want = "GET /pixel.gif";
    size_t want_len = strlen(want);
    char head[256];
    int head_len = snprintf(head, sizeof head,
                            "HTTP/1.1 200 OK\r\n"
                            "Content-Type: image/gif\r\n"
                            "Content-Length: %zu\r\n"
                            "Cache-Control: no-store\r\n"
                            "Connection: close\r\n\r\n",
                            sizeof GIF);
    const char *not_found = "HTTP/1.1 404 Not Found\r\nContent-Length: 0\r\nConnection: close\r\n\r\n";

    for (;;) {
        int c = accept(srv, NULL, NULL);
        if (c < 0) continue;
        char req[4096];
        ssize_t n = recv(c, req, sizeof req - 1, 0);
        if (n > 0) {
            req[n] = '\0';
            /* "GET /path HTTP/1.1" or "GET /path?query HTTP/1.1" */
            if (strncmp(req, want, want_len) == 0 && (req[want_len] == ' ' || req[want_len] == '?')) {
                send(c, head, (size_t) head_len, MSG_NOSIGNAL);
                send(c, GIF, sizeof GIF, MSG_NOSIGNAL);
            } else {
                send(c, not_found, strlen(not_found), MSG_NOSIGNAL);
            }
        }
        close(c);
    }
}

Mun gudanar da wannan snippet kuma mun kwatanta bytes ɗin da ya mayar.

Duba shi

curl -sI http://localhost:8080/pixel.gif

Shafin hukuma: C with POSIX sockets (no dependencies)

Ƙari a C