该程序为《UNIX网络编程》第一卷中第一章出现的程序, 该程序经过本人测试通过。
操作系统:CentOS 7
编译器:GCC
时间获取的服务器程序如下:
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <time.h>
#define MAX 1024
int main(int argc, char **argv)
{
int listenfd, connfd;
struct sockaddr_in servaddr;
char buff[MAX];
time_t ticks;
if((listenfd = socket(AF_INET, SOCK_STREAM, 0))<0)
{
perror("socket fail");
return 1;
}
bzero(&servaddr, sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
servaddr.sin_port = htons(13); /* daytime server */
bind(listenfd, (struct sockaddr *) &servaddr, sizeof(servaddr));
listen(listenfd, 10);
while(1)
{
connfd = accept(listenfd, (struct sockaddr *) NULL, NULL);
ticks = time(NULL);
snprintf(buff, sizeof(buff), "%.24s\r\n", ctime(&ticks));
write(connfd, buff, strlen(buff));
close(connfd);
}
return 0;
}
时间获取的客户端程序如下:
#include <sys/types.h>
#include <sys/socket.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <stdio.h>
#define PORT 13
#define MAXLINE 1024
int main(int argc, char **argv)
{
int sockfd, n;
char recvline[MAXLINE + 1];
struct sockaddr_in servaddr;
if (argc != 2)
puts("usage: t.out <IPaddress>");
if ( (sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0)
perror("socket error");
bzero(&servaddr, sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_port = htons(PORT);
if (inet_pton(AF_INET, argv[1], &servaddr.sin_addr) <= 0)
printf("inet_pton error for %s", argv[1]);
if (connect(sockfd, (struct sockaddr *) &servaddr, sizeof(servaddr)) < 0)
perror("connect error");
while ( (n = read(sockfd, recvline, MAXLINE)) > 0)
{
recvline[n] = 0;
if (fputs(recvline, stdout) == EOF)
perror("fputs error");
}
if (n < 0)
perror("read error");
exit(0);
}
编译服务器程序:
[root@mylinux 1]# gcc -o time_s time_s.c
编译客户端程序:
[root@mylinux 1]# gcc -o t.out time_c.c
接下来首先运行服务器程序:
[root@mylinux 1]# ./time_s
然后运行客户端程序,得到服务器返回的时间:
[root@mylinux 1]# ./t.out 127.0.0.1
Sat Sep 10 09:36:03 2016