在 Ubuntu 上從零撰寫一個極簡 HTTP 伺服器,監聽 1024 埠,支援 gzip 壓縮回應,驗證壓縮頭部格式與 zlib 串流壓縮流程。適合學習 HTTP 協定、zlib 用法、Socket 程式設計。
#include <zlib.h>
#define DEFAULT_BUFFERSIZE 8096
static const char gzip_header[10] = {0x1f, 0x8b, Z_DEFLATED, 0, 0, 0, 0, 0, 0, 0x03}; // RFC 1952 標準 gzip header
int gzip_buffer(int sockd, char *msg, int len) {
z_stream stream;
char in[DEFAULT_BUFFERSIZE];
char send[DEFAULT_BUFFERSIZE + 18]; // header(10) + data + trailer(8)
memcpy(send, gzip_header, 10);
memcpy(in, msg, len);
stream.zalloc = Z_NULL;
stream.zfree = Z_NULL;
stream.opaque = Z_NULL;
deflateInit2(&stream, Z_DEFAULT_COMPRESSION, Z_DEFLATED, -MAX_WBITS, 8, Z_DEFAULT_STRATEGY);
stream.avail_in = len;
stream.next_in = (Bytef*)in;
stream.avail_out = DEFAULT_BUFFERSIZE;
stream.next_out = (Bytef*)(send + 10);
deflate(&stream, Z_FINISH);
unsigned have = DEFAULT_BUFFERSIZE - stream.avail_out;
// CRC32 + ISIZE (原始長度) 寫入 trailer
unsigned long crc = crc32(0L, (Bytef*)in, len);
char *tail = send + 10 + have;
tail[0] = crc & 0xff; tail[1] = (crc>>8) & 0xff; tail[2] = (crc>>16) & 0xff; tail[3] = (crc>>24) & 0xff;
tail[4] = len & 0xff; tail[5] = (len>>8) & 0xff; tail[6] = (len>>16) & 0xff; tail[7] = (len>>24) & 0xff;
write(sockd, send, have + 18);
deflateEnd(&stream);
return 1;
}
# 安裝 zlib 開發套件
sudo apt-get install zlib1g-dev
# 編譯
gcc -o reage_web reage_web.c -lz
# 執行(需 root 權限綁定 1024 以下埠,或改用 >1024 埠)
./reage_web
# 瀏覽器訪問 https://localhost:1024 應看到壓縮後的 HTML 內容
0x1f 0x8b、壓縮方法 Z_DEFLATED、旗標、修改時間、額外旗標、OS 代碼(0x03=Unix)。windowBits = -MAX_WBITS 表示輸出 gzip 格式(而非 zlib/raw deflate)。Content-Encoding: gzip,否則瀏覽器不會解壓。Accept-Encoding 協商壓縮。