简单的CGI服务器

CGI服务器主要是通过把服务器本地标准输入,输出或者文件重定向到网络连接中,这样我们就能够通过向标准输入,输出缓冲区中发送信息,达到在网络连接中发送信息的效果.,(简单理解。。。。)
这里主要注意点是我们要进行fflush(),通过dup进行重定向
cgi.c

#include <sys/socket.h>
#include <errno.h>
#include <string.h>
#include <arpa/inet.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

#define LISTENQ 100

int main(int argc,char** argv) {
    if (argc != 2) {
        printf("please add <port>");
        return 1;
    }
    int sockfd;
    if ((sockfd = socket(AF_INET,SOCK_STREAM,0)) < 0) {
        printf("socket error: %s\n",strerror(errno));
        return 1;
    }
    struct sockaddr_in addr;
    addr.sin_family = AF_INET;
    addr.sin_addr.s_addr = htonl(INADDR_ANY);
    addr.sin_port = htons(atoi(argv[1]));
    if (bind(sockfd,(struct sockaddr*)&addr,sizeof(addr)) < 0) {
        printf("bind error: %s\n",strerror(errno));
        return 1;
    }
    if (listen(sockfd,LISTENQ) < 0) {
        printf("listen error: %s\n",strerror(errno));
        return 1;
    }
    int connfd;
    for ( ; ;) {
        if ((connfd = accept(sockfd,NULL,NULL)) < 0) {
            if (errno == EINTR) {
                continue;
            }
            printf("accept error: %s\n",strerror(errno));
            return 1;
        }
        int ret = close(STDOUT_FILENO);
        if (ret < 0) {
            printf("close error: %s",strerror(errno));
            exit(1);
        }
        if (dup(connfd) < 0) {
            printf("dup error: %s\n",strerror(errno));
            return 1;
        }
        printf("which is server send by STDOUT_FILENO\n");
        fflush(stdout);
        close(connfd);
    }
    return 0;
}

通过telnet测试:

这里写图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值