Unix Network Programming Episode 81

#include "unp.h"

int tcp_listen(const char *host, const char *serv, socklen_t *addrlenp)
{
    int listenfd, n;
    const int on=1;
    struct addrinfo hints, res, &ressave;

    bzero(&hints, sizeof(struct addrinfo));
    hints.ai_flags=AI_PASSIVE;
    hints.ai_family=AF_UNSPEC;
    hints.ai_socktype=SOCK_STREAM;

    if((n=getaddrinfo(host,serv,&hints, &res))!=0)
        err_quit("tcp_listen error for %s, %s: %s", host ,serv, gai_strerror(n));
    
    ressave=res;

    do{
        listenfd=socket(res->ai_family, res->ai_socktype, res->ai_protocol);
        if(listenfd<0)
            continue;
        Setsockopt(listenfd, SOL_SOCKET, SO_RESUSEADDR,&on, sizeof(on));
        if(bind(listenfd, res->ai_addr, res->ai_addrlen)==0)
            break;
        Close(listenfd);
    }while((res=res->ai_next)!=NULL);

    if(res==NULL)
        err_sys("tcp_listen error for %s, %s", host, serv);
    Listen(listenfd, LISTENQ);

    if(addrlenp)
        *addrlenp=res->ai_addrlen;
    freeaddrinfo(ressave);
    return listenfd;
}

tcp_listen function: performs normal server steps

#include "unp.h"
#include <time.h>

int main(int argc, char **argv)
{
    int listenfd, connfd;
    socklen_t len;
    char buff[MAXLINE];
    time_t ticks;
    struct sockaddr_storage clientaddr;

    if(argc!=2)
        err_quit("usage: daytimetcpserv1 <service or port#>");
    
    listenfd=Tcp_listen(NULL, argv[1], NULL);

    for(;;)
    {
        len=sizeof(clientaddr);
        connfd=Accept(listenfd, (SA *) &clientaddr, &len);
        printf("connection from %s\n",Sock_ntop((SA *)&clientaddr, len));
        ticks=time(NULL);
        snprintf(buff, sizeof(buff),"%.24s\r\n",ctime(&ticks));
        Write(connfd, buff, strlen(buff));

        Close(connfd);
    }
}

Daytime server recoded to use tcp_listen (see also Figure 11.14)

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值