CGI 環境變數包含很多有用的訊息,包含 AUTHORIZATION,QUERY_STRING,CONTENT_LENGTH 等。只要使用 getenv 函數直接讀取即可。如要讀取所有變數則使用 main 的第三個參數來分析。

參考網址:http://ccckmit.wikidot.com/cgi:env

#include <stdio.h> #include <unistd.h> #include <stdlib.h> int main(int argc, char *argv[], char *envp[]) { int i; int cgi_fd; char *query = getenv("QUERY_STRING"); // redirect stderr to console freopen("/dev/console", "w", stderr); fprintf(stderr, "enos[%s:%d,%s]start\n", __FILE__, __LINE__, __func__); fprintf(stderr, "enos[%s:%d,%s]%s\n", __FILE__, __LINE__, __func__, query); for(i=0; envp[i]!=NULL; ++i) { fprintf(stderr, "%s\n", envp[i]); } // open cgi fd cgi_fd = dup(STDOUT_FILENO); if (cgi_fd < 0) cgi_fd = STDOUT_FILENO; // return 403 dprintf(cgi_fd, "Status: 401 Unauthorized\r\n"); dprintf(cgi_fd, "WWW-Authenticate: Basic realm=\"Web Server Authentication\"\r\n\r\n"); // stop fprintf(stderr, "enos[%s:%d,%s]stop\n", __FILE__, __LINE__, __func__); fclose(stderr); return 0; }

console 輸出結果

enos[main.c:13,main]start enos[main.c:14,main](null) SERVER_SOFTWARE=lighttpd/1.4.28 SERVER_NAME=192.168.1.102 GATEWAY_INTERFACE=CGI/1.1 SERVER_PROTOCOL=HTTP/1.1 SERVER_PORT=80 SERVER_ADDR=0.0.0.0 REQUEST_METHOD=GET REDIRECT_STATUS=200 REQUEST_URI=/cgi-bin/media-server REMOTE_ADDR=192.168.1.103 REMOTE_PORT=54549 CONTENT_LENGTH=0 SCRIPT_FILENAME=/var/www/cgi-bin/media-server SCRIPT_NAME=/cgi-bin/media-server DOCUMENT_ROOT=/var/www/realtek HTTP_ACCEPT=*/* HTTP_ACCEPT_LANGUAGE=zh-TW HTTP_USER_AGENT=Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; Tablet PC 2.0) HTTP_ACCEPT_ENCODING=gzip, deflate HTTP_HOST=192.168.1.102 HTTP_CONNECTION=Keep-Alive HTTP_CACHE_CONTROL=no-cache HTTP_AUTHORIZATION=Basic MTIzOjExMQ== enos[main.c:28,main]stop
創作者介紹

邱小新の工作筆記

台南小新 發表在 痞客邦 PIXNET 留言(0) 人氣()