为网络上的用户提供时间服务,即为网络用户返回服务器的当前时间;
记录发出请求的网络用户的IP地址(保存到文件中);
编写时间服务客户端timeclient,该客户端能够向服务器发送时间服务请求,并把获得的时间返回给用户。
开发环境:fedora13,vim,gcc
timeserver.c文件
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 |
#include<stdio.h> #include<unistd.h> #include<sys/types.h> #include<sys/socket.h> #include<netinet/in.h> #include<arpa/inet.h> #include<time.h> #include<netdb.h> #include<stdlib.h> #include<string.h> #define PORT 1234 #define BACKLOG 5 int main() { int listenfd, connectfd; struct sockaddr_in server; struct sockaddr_in client; socklen_t addrlen; time_t t; t=time(NULL); FILE *fd=fopen("/root/saveIP","a"); if((listenfd = socket(AF_INET, SOCK_STREAM, 0)) == -1) { perror("socket() error."); return 0; } int opt = SO_REUSEADDR; setsockopt(listenfd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt)); bzero(&server, sizeof(server)); server.sin_family = AF_INET; server.sin_port = htons(PORT); server.sin_addr.s_addr = htonl(INADDR_ANY); if(bind(listenfd, (struct sockaddr *)&server, sizeof(server)) == -1) { perror("bind() error."); return 0; } if(listen(listenfd, BACKLOG) == -1) { perror("listen() error."); return 0; } addrlen = sizeof(client); if((connectfd = accept(listenfd, (struct sockaddr *)&client, &addrlen )) == -1) { perror("accept() error."); return 0; } printf("Timeclient's IP is %s. ",inet_ntoa(client.sin_addr)); printf("Time is %s\n",ctime(&t)); send(connectfd,(time_t *)&t,sizeof(time_t),0); fprintf(fd,"%s %s\n",inet_ntoa(client.sin_addr),ctime(&t)); fclose(fd); return 1; } |
timeclient.c文件
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 |
#include<stdio.h> #include<stdlib.h> #include<unistd.h> #include<strings.h> #include<sys/types.h> #include<sys/socket.h> #include<netinet/in.h> #include<netdb.h> #define PORT 1234 /*listen port*/ int main ( int argc, char *argv[]) { int sockfd, num; struct hostent *he; struct sockaddr_in server; time_t t; if(argc!=2) { printf("usage %s<ip address>\n",argv[0]); return 0; } /*get ip address*/ if((he = gethostbyname(argv[1])) == NULL) { printf("gethostbyname error\n"); return 0; } if((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1) { printf("socket() error \n"); return 0; } bzero(&server, sizeof(server)); server.sin_family = AF_INET; server.sin_port = htons(PORT); server.sin_addr = *((struct in_addr *)he->h_addr); if(connect(sockfd, (struct sockaddr *)&server, sizeof(server)) == -1) { printf("connetc() error\n"); return 0; } recv(sockfd,(void *)&t,sizeof(time_t),0); printf("Time is %s\n",ctime(&t)); } |
发表评论
要发表评论,您必须先登录。