libhttpd的使用

37 篇文章 3 订阅
20 篇文章 0 订阅

LibHttpd是一个开源轻量级嵌入式Web server,LibHttpd实现了下述功能:

  • 实现了HTTP的子集;
  • 使用表格技术自动处理Html Form数据;
  • 产生的内容既可以是静态的网页,也可以是调用C函数动态产生的(callback);
  • LibHttpd提供API,利用这些API,用户可以很方便地将自己的Web内容加入到程序当中。

libhttpd中带有英文的使用手册,也增加了使用实例源码,在编程中可以做一个很好的模板:

#include "config.h"

#include <stdio.h>
#include <unistd.h>
#include <signal.h>

#ifdef _WIN32
#  include <getopt.h>
#else
#  include <sys/time.h>
#endif

#include "httpd.h"

/*
** This is a static page of HTML.  It is loaded into the content
** tree using httpdAddStaticContent( ).
*/
#define test1_html "<HTML><BODY>This is just a test</BODY>"

#define ember_code1 "printf(\"This is from ember in process %d\n\",getpid());"
#define ember_code "load \"/usr/local/nk/www/content.lib\"; dispatchWebPage(\"/index.html\");"

/*
** Below are 2 dynamic pages, each generated by a C function.  The first
** is a simple page that offers a little dynamic info (the process ID)
** and the setups up a test link and a simple form.
** 
** The second page processes the form.  As you can see, you can access
** the form data from within your C code by accessing the symbol table
** using httpdGetVariableByName() (and other similar functions).  You
** can also include variables in the string passed to httpdOutput( ) and
** they will be expanded automatically.
*/
void index_html(server)
    httpd   *server;
{
    httpdPrintf(server,
        "Welcome to the httpd server running in process number %d<P>\n",
        getpid());
    httpdPrintf(server,
        "Click <A HREF=/test1.html>here</A> to view a test page<P>\n");
    httpdPrintf(server,
        "Click <A HREF=/login.html>here</A> to authenticate<P>\n");
    httpdPrintf(server,
        "Or <A HREF=/wildcard/foo>here</A> for a test wildcard page<P>\n");
    httpdPrintf(server, "<P><FORM ACTION=test2.html METHOD=POST>\n");
    httpdPrintf(server, "Enter your name <INPUT NAME=name SIZE=10>\n");
    httpdPrintf(server, "<INPUT TYPE=SUBMIT VALUE=Click!><P></FORM>\n");
    return;
}

void test2_html(server)
    httpd   *server;
{
    httpVar *variable;

    /*
    ** Grab the symbol table entry to see if the variable exists
    */
    variable = httpdGetVariableByName(server, "name");
    if (variable == NULL)
    {
        httpdPrintf(server,"Missing form data!");
        return;
    }

    /*
    ** Use httpdOutput() rather than httpdPrintf() so that the variable
    ** embedded in the text is expanded automatically
    */
    httpdOutput(server,"Hello $name");
}

void test3_html(server)
    httpd   *server;
{
    char    *path;

    path = httpdRequestPath(server);
    httpdOutput(server,"Wilcard dynamic request received<P>");
    httpdPrintf(server,"The requested path was %s<P>", path);
}


void login_html(server)
    httpd   *server;
{
    if (httpdAuthenticate(server, "LibHTTPD Test") == 0)
        return;
    httpdPrintf(server, "Your username is '%s'<P>\n",
        server->request.authUser);
    httpdPrintf(server, "Your password is '%s'<P>\n",
        server->request.authPassword);
    httpdOutput(server, 
        "Click <A HREF=login2.html>here</A> to force reauthentication");
    httpdOutput(server, ".  Use a username = test password = 123");
}



void login2_html(server)
    httpd   *server;
{
    if (httpdAuthenticate(server, "LibHTTPD Test") == 0)
    {
        httpdOutput(server, "Authentication failure(1).");
        return;
    }
    if (strcmp(server->request.authUser, "test") != 0 ||
        strcmp(server->request.authPassword, "123") != 0)
    {
        httpdForceAuthenticate(server, "LibHTTPD Test");
        httpdOutput(server, "Authentication failure (2).");
        return;
    }
    httpdOutput(server, "Your login was accepted.");
}


void myError404Handler(server, error)
    httpd   *server;
    int error;
{
    httpdOutput(server,"Whoa there.  You hit a page that doesn't exist! <P><BR><BR>\n");
    httpdOutput(server,"Or in other words : <B>Error 404</B>\n\n");
}


int main(argc, argv)
    int argc;
    char    *argv[];
{
    httpd   *server;
    char    *host;
    int     port,
        errFlag,
        result;
    extern char *optarg;
    extern int optind, opterr, optopt;
    int c;
    struct  timeval timeout;

    host = NULL;
    port = 80;
    errFlag = 0;
    while ( (c=getopt(argc,argv,"h:p:")) != -1 )
    {
        switch ( c ) 
        {
            case 'h':
                host=optarg;
                break;

            case 'p':
                port = atoi(optarg);
                break;
            default:
                errFlag++;
        }
    }
    if (errFlag)
    {
        fprintf(stderr,"usage: [-h <host IP>] [ -p <port >]\n");
        fprintf(stderr,"\nLibHTTPD version %s\n\n",LIBHTTPD_VERSION);
        exit(1);
    }


    /*
    ** Ensure that PIPE signals are either handled or ignored.
    ** If a client connection breaks while the server is using
    ** it then the application will be sent a SIGPIPE.  If you
    ** don't handle it then it'll terminate your application.
    */
    signal(SIGPIPE, SIG_IGN);


    /*
    ** Create a server and setup our logging
    */
    server = httpdCreate(host,port);
    if (server == NULL)
    {
        perror("Can't create server");
        exit(1);
    }
    httpdSetAccessLog(server, stdout);
    httpdSetErrorLog(server, stdout);

    /*
    ** We are fussy and don't want the default Error 404 page
    */
    httpdSetErrorFunction(server,404, myError404Handler);


    /*
    ** Setup some content for the server
    */
    httpdAddCContent(server,"/", "index.html", HTTP_TRUE, 
        NULL, index_html);
    httpdAddCContent(server,"/", "test2.html", HTTP_FALSE, 
        NULL, test2_html);
    httpdAddCContent(server,"/", "login.html", HTTP_FALSE,
        NULL, login_html);
    httpdAddCContent(server,"/", "login2.html", HTTP_FALSE,
        NULL, login2_html);
    httpdAddCWildcardContent(server,"/wildcard", NULL, test3_html);
    httpdAddStaticContent(server, "/", "test1.html", HTTP_FALSE,
        NULL, test1_html);
    httpdAddEmberContect(server,"/","ember.html", HTTP_FALSE, 
        NULL, ember_code);

    /*
    ** Go into our service loop
    */

    while(1 == 1)
    {
        /*
        ** Linux modifies the timouet value during the
        ** select call so we must set it everyt ime.  Most
        ** other UNIX implementations do not modify timeout
        ** but it doesn't hurt to set it each time anyway
        */
        timeout.tv_sec = 5;
        timeout.tv_usec = 0;
        result = httpdGetConnection(server, &timeout);
        if (result == 0)
        {
            printf("Timeout ... \n");
            continue;
        }
        if (result < 0)
        {
            printf("Error ... \n");
            continue;
        }
        if(httpdReadRequest(server) < 0)
        {
            httpdEndRequest(server);
            continue;
        }
        httpdProcessRequest(server);
        httpdEndRequest(server);
    }
}

以下转载于网络博客中关于libhttpd接口函数的功用,更详细的函数功能参看libhttpd manual:

----------------------------------------------------------------------------------
httpdCreate ( ) 创建WEB服务器

httpd * httpdCreate ( host , port )  
 char * host 
 int port 
Example :  
 server = httpdCreate( “192.168.1.1”, HTTP_PORT);
 if ( server == NULL )  
     perror ( “Couldn’t create HTTP server” ); 

 server2 = httpdCreate ( NULL , 2048 );
------------------------------------------------------------------------------------
httpdSetAccessLog( ) 设置访问日志文件
httpdSetAccessLog ( server, fp )  
 httpd *server; 
 FILE *fp;
Example :  
 fp = fopen ( “/tmp/access.log”, “a” ); 
 httpdSetAccessLog ( server, fp );

--------------------------------------------------------------------
httpdSetErrorLog( ) 设置错误日志文件
httpdSetErrorLog ( server, fp )  
 httpd *server; 
 FILE *fp;
Example :  
 httpdSetErrorLog ( server, stderr );
------------------------------------------------------------------------
httpdSetFileBase( ) 设置文件基本路径名

httpdSetErrorLog ( server, path )  
 httpd *server; 
 char *path;
Example :  
 httpdSetFileBase ( server, “/usr/local/www-pages” );
------------------------------------------------------------------------
httpdAddCContent( ) 调用C函数产生输出内容

httpdAddCContent ( server, dir, name, indexFlag, preload, functPtr )  
 httpd *server; 
 char *dir, *name; 
 int  indexFlag, (*)( )preload; 
 void  (*)( ) functPtr;
Example :  
 void index_callbackl ( server ) 
   httpd *server; 
 { 
    httpdOutput(server, “<HTML><BODY>Hello There</BODY></HTML>\n”); 
 } 

 httpdAddCContent( server, “/”, “index.html”, HTTP_TRUE, NULL, index_callback); 
------------------------------------------------------------------------------------
httpdAddFileContent( ) 将一个外部文件加入到输出内容
httpdAddFileContent ( server, dir, name, indexFlag, preload, path )  
 httpd *server; 
 char *dir, *name; 
 int  indexFlag, (*) ( ) preload; 
 char *path;
Example :  
 httpdAddFileContent( server, “/”, “index.html”, HTTP_TRUE, NULL,  “/usr/local/www/index.html” );
-----------------------------------------------------------------------------------
httpdAddStaticContent( ) 将一个内部文本BUFFER加入到HTML输出内容
httpdAddStaticContent ( server, dir, name, indexFlag, preload, buf )  
 httpd *server; 
 char *dir, *name; 
 int  indexFlag, (*)( ) preload; 
 char *buf;
Example :  
 #define index_content “<HTML><BODY>Hello There</BODY></HTML>\n” 
 httpdAddStaticContent( server, “/”, “index.html”, HTTP_TRUE, NULL, index_content );
------------------------------------------------------------------------------------
httpdAddWildcardContent( ) 增加与通配符匹配的文件内容

httpdAddWildcardContent ( server, dir, preload, path )  
 httpd *server; 
 char *dir; 
 int  (*) ( )preload; 
 char *path;
Example :  
        httpdAddWildcardContent(server,“/graphics”, NULL, “/usr/local/www/graphics” );
-----------------------------------------------------------------------------------
httpdAddCWildcardContent( ) 请求指定目录中的任何文件时调用C回调函数
httpdAddCWildcardContent ( server, dir, preload, functPtr )  
 httpd *server; 
 char *dir; 
 int  (*) ( )preload; 
 void  (*)( ) functPtr;
Example :  
      httpdAddCWildcardContent(server,“/users”, NULL, send_user_info );
---------------------------------------------------------------------------------
httpdGetConnection ( ) 接受一个HTTP连接请求
int httpdGetConnection ( server , timeout)  
 httpd *server; 
 struct timeval *timeout;
-----------------------------------------------------------------------
httpdReadRequest ( ) 读取并保存从客户端发送过来的请求和数据
int httpdReadRequest ( server )  
 httpd *server;
-------------------------------------------------------------------------
httpdProcessRequest ( ) 对请求进行处理,并将请求内容发送到客户端浏览器

httpdProcessRequest ( server )  
 httpd *server;
----------------------------------------------------------------------
httpdEndRequest ( ) 请求结束处理

httpdEndRequest ( server )  
 httpd *server;
----------------------------------------------------------------------
httpdOutput ( ) 将文本BUFFER内容发送到客户端浏览器
httpdOutput ( server, buffer )  
 httpd *server; 
 char *buffer
Example :  
 httpdOutput ( server, “Hello $name. Welcome to the test server” );
----------------------------------------------------------------------
httpdPrintf ( ) 按指定格式将内容输出到客户端浏览器

httpdPrintf ( server, format, arg, arg, … )  
 httpd *server; 
 char *format;
Example :  
 httpdPrintf( server, “Hello %s.  Welcome to the server running in process number %d”, 
 username, getpid( )  );
-------------------------------------------------------------------------
httpdSetContentType ( ) 设置除HTML文本以外的内容类型

httpdSetContentType( server, type )  
 httpd *server; 
 char *type
Example :  
 httpdSetContentType ( server, “image/jpeg” );
------------------------------------------------------------------------
httpdSetResponse ( ) 设置返回给客户端浏览器的的响应代码
httpdSetResponse( server, responseInfo )  
 httpd *server; 
 char *responseInfo;
Example :  
 httpdSetResponse ( server, “301 Moved Permanently” );
-------------------------------------------------------------------
httpdAddHeader ( ) 增加HTML头内容

httpdAddHeader( server, header )  
 httpd *server; 
 char *header;
Example :  
 httpdSetResponse ( server, “307 Temporary Redirect” ); 
 httpdAddHeader ( server, “Location: http://www.foo.com/some/new/location”);
---------------------------------------------------------------------------------
httpdSendHeaders( ) 发送HTML头

httpdSendHeaders( server)  
 httpd *server;
Example :  
 httpdSetContentType ( server, “image/jpeg” ); 
 httpdSendHeaders ( server ); 
 generateJpegData( server );
---------------------------------------------------------------------------------
httpVar * httpdGetVariableByName ( ) 在符号表中查找变量
httpdGetVariableByName( server, varName )  
 httpd *server; 
 char *varName;
Example :  
 varPtr = httpdGetVariableByName ( server, “username” ); 
 if ( varPtr != NULL) 
 uname = varPtr->value ;
------------------------------------------------------------------------------
httpVar * httpdGetVariableByPrefix ( ) 获取第一个与指定前缀相匹配的变量
httpdGetVariableByPrefixe( server, prefix )  
 httpd *server; 
 char *prefix;
-------------------------------------------------------------------------
httpVar * httpdGetNextVariableByPrefix ( ) 获取下一个与指定前缀相匹配的变量
httpdGetNextVariableByPrefixe( varPtr, prefix )  
 httpVar *varPtr; 
 char *prefix;

Example :  
 varPtr = httpdGetVariableByPrefix ( server, “hughes_” ); 
 while ( varPtr != NULL )  
 { 
          printf(“Name = %s, Value = %s \n”, varPtr->name, varPtr->value; 
     varPtr = httpdGetNextVariableByPrefix ( varPtr, “hughes_” ); 
 }

------------------------------------------------------------------------
httpVar * httpdGetVariableByPrefixedName ( ) 在符号表中查找变量
httpdGetVariableByPrefixedName( varPtr, prefix, remainder )  
 httpVar *varPtr; 
 char  *prefix, *remainder; 
Example :  
 prefixPtr = httpdGetVariableByName ( server, “multi-select-values” ); 
 while ( prefixPtr != NULL ) 
 { 
    prefix = prefixPtr->value; 
    varPtr = httpdGetVariableByPrefixedName(server, prefix, “_username”); 
    printf(“%s_username = %s\n”, prefix, varPtr->value; 
    prefixPtr = prefixPtr->nextValue; 
 } 

------------------------------------------------------------------------------
httpdAddVariable( ) 在符号表中增加变量
httpdAddVariable( server, name, value )  
 httpd *server; 
 char  *name, *value; 
Example :  
 httpdAddVariable( server, “background_color”, “#FFFF30” ); 
 httpdOutput( server, “<BODY BGCOLOR=$background_color>\n”);
---------------------------------------------------------------------------
httpdDumpVariables( ) Dump符号表内容

httpdDumpVariables( server )  
 httpd *server;
-------------------------------------------------------------------------
httpdSet( ) 设置
httpdSet( server, name, value )  
 httpd *server; 
 char *name, *value;
---------------------------------------------------------------------------
httpdAuthenticate( ) 使用用户名和口令进行身份认证

httpdAuthenticate( server, realm )  
 httpd *server; 
 char *realm;
---------------------------------------------------------------------------
httpdForceAuthenticate( ) 强迫身份认证

httpdForceAuthenticate( server, realm )  
 httpd *server; 
 char *realm;
------------------------------------------------------------------------------
httpdAddAcl( ) 在ACL表中增加访问控制项

httpdAddAcl( server, acl, cidrAddr, action )  
 httpd *server; 
 httpAcl *acl; 
 char *cidrAddr; 
 int action
-----------------------------------------------------------------------------
httpdSetDefaultAcl( ) 设置默认ACL

httpdSetDefaultAcl( server, acl )  
 httpd *server; 
 httpAcl *acl;
--------------------------------------------------------------------
httpdCheckAcl( ) 进行ACL检查

httpdCheckAcl( server, acl )  
 httpd *server; 
 httpAcl *acl;
-------------------------------------------------------------------
httpdUrlEncode( ) 进行URL解码

char * httpdUrlEncode( buf )  
 char *buf;
-------------------------------------------------------------------
httpdRequestMethod( ) 获取访问方式(HTTP_GET/HTTP_POST)

int httpdRequestMethod( server )  
 httpd *server;
--------------------------------------------------------------------
httpdRequestMethodName( ) 获取访问方式名字

char *httpdRequestMethodName( server )  
 httpd *server;
------------------------------------------------------------------
httpdRequestPath( ) 获取URL请求路径
char *httpdRequestPath( server )  
 httpd *server;
----------------------------------------------------------------------
httpdRequestContentType( ) 获取当前请求内容类型
char *httpdRequestContentType( server )  
 httpd *server;
-----------------------------------------------------------------------
httpdRequestContentLength( ) 获取当前请求发送的内容长度

int httpdRequestContentLength( server )  
 httpd *server;
-----------------------------------------------------------------------
  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值