UNP卷1:第一章(简介)

最后更新于:2022-04-01 14:48:51

1. 时间获取程序 服务端:srv.c ~~~ #include <time.h> #include <stdio.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <stdlib.h> #include <fcntl.h> #define SA struct sockaddr #define MAXLINE 1024 int main( void ) { int listenfd, connfd; struct sockaddr_in servaddr; char buff[ MAXLINE ]; time_t ticks; pid_t pid; 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(7777); bind(listenfd, ( SA * )&servaddr, sizeof(servaddr)); listen( listenfd, 5 ); for( ; ; ){ connfd = accept( listenfd, ( SA * )NULL, NULL); pid = fork(); if ( 0 == pid ){ ticks = time( NULL ); snprintf(buff, sizeof(buff), "%.24s\r\n", ctime(&ticks)); write( connfd, buff, strlen(buff)); exit(1); } if ( waitpid(pid, NULL,0 ) != pid ){ printf("waitpid error"); exit(1); } close( connfd ); } return 0; } ~~~ 客户端:cli.c ~~~ #include <stdio.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <stdlib.h> #define SA struct sockaddr #define MAXLINE 1024 int main( int argc, char **argv ) { int sockfd, n; char recvline[ MAXLINE + 1 ]; struct sockaddr_in servaddr; if ( argc != 2 ){ printf("usage:a.out <IPaddress>"); exit(1); } if ( ( sockfd = socket( AF_INET, SOCK_STREAM, 0 ) ) < 0 ){ printf("socket error\n"); exit(1); } bzero( &servaddr, sizeof( servaddr ) ); servaddr.sin_family = AF_INET; servaddr.sin_port = htons( 7777 ); if ( inet_pton( AF_INET, argv[ 1 ], &servaddr.sin_addr ) <= 0 ){ printf("inet_pton error for %s", argv[1]); exit(1); } if ( connect( sockfd, ( SA * )&servaddr, sizeof( servaddr ) ) < 0 ){ printf("connect error\n"); exit(1); } while ( ( n = read( sockfd, recvline, MAXLINE )) > 0){ recvline[n] = 0; if (fputs(recvline, stdout) == EOF){ printf("fputs error\n"); exit(1); } } if (n < 0){ printf("read error\n"); exit(1); } exit(0); } ~~~ 运行结果如下: 服务端: ~~~ root@ThinkPad-T430i:/home/leichaojian# lsof -i:7777 root@ThinkPad-T430i:/home/leichaojian# cc srv.c root@ThinkPad-T430i:/home/leichaojian# ./a.out ~~~ 客户端: ~~~ leichaojian@ThinkPad-T430i:~$ ./a.out 127.0.0.1 Fri Sep 5 00:14:14 2014 ~~~ **这里lsof -i:7777是必要的,否则端口会被占用,导致connect失败!** 对于习题1.5,修改代码如下: ~~~ for ( count = 0; count < strlen( buff ); count++ ) write( connfd, &buff[ count ], 1 ); ~~~    但是客户端依旧只返回1,即虽然服务端是分字符write,但实际上还是一次性的发送所有的数据。
';