• unp的hello word


    最近无聊,再学学unp吧。学学网络编程。下面是一个demo:

    intro/daytimetcpcli.c
    #include    "unp.h"
    
    int
    main(int argc, char **argv)
    {
        int                    sockfd, n;
        char                recvline[MAXLINE + 1];
        struct sockaddr_in    servaddr;
    
        if (argc != 2)
            err_quit("usage: a.out <IPaddress>");
    
        if ( (sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0)
            err_sys("socket error");
    
        bzero(&servaddr, sizeof(servaddr));
        servaddr.sin_family = AF_INET;
        servaddr.sin_port   = htons(8888);    /* daytime server */
        if (inet_pton(AF_INET, argv[1], &servaddr.sin_addr) <= 0)
            err_quit("inet_pton error for %s", argv[1]);
    
        if (connect(sockfd, (SA *) &servaddr, sizeof(servaddr)) < 0)
            err_sys("connect error");
    
        while ( (n = read(sockfd, recvline, MAXLINE)) > 0) {
            recvline[n] = 0;    /* null terminate */
            if (fputs(recvline, stdout) == EOF)
                err_sys("fputs error");
        }
        if (n < 0)
            err_sys("read error");
    
        exit(0);
    }
    intro/daytimetcpsrv.c
    #include    "unp.h"
    #include    <time.h>
    
    int
    main(int argc, char **argv)
    {
        int                    listenfd, connfd;
        struct sockaddr_in    servaddr;
        char                buff[MAXLINE];
        time_t                ticks;
    
        listenfd = Socket(AF_INET, SOCK_STREAM, 0);
    
        bzero(&servaddr, sizeof(servaddr));
        servaddr.sin_family      = AF_INET;
        servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
        servaddr.sin_port        = htons(8888);    /* daytime server */
    
        Bind(listenfd, (SA *) &servaddr, sizeof(servaddr));
    
        Listen(listenfd, LISTENQ);
    
        for ( ; ; ) {
            connfd = Accept(listenfd, (SA *) NULL, NULL);
    
            ticks = time(NULL);
            snprintf(buff, sizeof(buff), "%.24s
    ", ctime(&ticks));
            Write(connfd, buff, strlen(buff));
    
            Close(connfd);
        }
    }

    下面说一下怎么运行。

    dzhwen@deng:~/unpv13e/intro$ gcc -w daytimetcpsrv.c ../lib/wrapsock.c ../lib/error.c ../lib/wrapunix.c -o testsrv
    dzhwen@deng:~/unpv13e/intro$ gcc -w daytimetcpcli.c ../lib/error.c -o test
    dzhwen@deng:~/unpv13e/intro$ ./testsrv
    dzhwen@deng:~/unpv13e/intro$ ./test 127.1.1.1
    Thu May  8 23:49:43 2014

    成功!

  • 相关阅读:
    文本框字数减少
    区分兼容IE6/IE7/IE8/IE9/FF的CSS HACK写法
    将浏览器兼容代码标明信息并相互分开
    JavaScript正则表达式
    CSS3 @font-face
    iOS 获取手机的使用存储信息
    升级 ox 10.11的系统以后执行 pod install 的时候报错
    Xcode7安装模拟器
    iOS-视图生命周期
    Xcode升级插件失效修复快捷方式
  • 原文地址:https://www.cnblogs.com/sysu-blackbear/p/3717955.html
Copyright © 2020-2023  润新知