码迷,mamicode.com
首页 > 其他好文 > 详细

unp的hello word

时间:2014-05-09 06:39:40      阅读:333      评论:0      收藏:0      [点我收藏+]

标签:style   blog   class   code   java   color   

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

bubuko.com,布布扣
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);
}
bubuko.com,布布扣
bubuko.com,布布扣
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\r\n", ctime(&ticks));
        Write(connfd, buff, strlen(buff));

        Close(connfd);
    }
}
bubuko.com,布布扣

下面说一下怎么运行。

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

成功!

unp的hello word,布布扣,bubuko.com

unp的hello word

标签:style   blog   class   code   java   color   

原文地址:http://www.cnblogs.com/sysu-blackbear/p/3717955.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!