C with POSIX sockets (no dependencies) C
C with POSIX sockets (no dependencies)-এর জন্য একটি C স্নিপেট, যা /pixel.gif-এ আসা রিকোয়েস্টের উত্তরে empty GIF পাঠায়। GIF-টি স্টার্টআপে একবারই ডিকোড হয়।
C with POSIX sockets (no dependencies) C
/* 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);
}
}
আমরা এই স্নিপেট চালিয়েছি এবং এটি যে বাইটগুলো ফেরত দিয়েছে তা মিলিয়ে দেখেছি।
যাচাই করুন
curl -sI http://localhost:8080/pixel.gif
অফিশিয়াল সাইট: C with POSIX sockets (no dependencies)