标签:style blog class code java color
最近无聊,再学学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\r\n", 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
成功!
标签:style blog class code java color
原文地址:http://www.cnblogs.com/sysu-blackbear/p/3717955.html