2011年(18)
分类: WINDOWS
2011-04-28 13:31:45
/********************************************** 作者:猪头流氓 时间:Sun Jan 7 02:46:39 2007 文件名:server.c 描述: **********************************************/ #include #include #include #include #include #include #include #include int sendtime(int fd); void print_date(); int main() { int sockfd; struct sockaddr_in my_addr; struct sockaddr_in their_addr; int newfd; char buf[10]; int sockaddr_len; int rt; if((sockfd = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP)) <= 0) { perror("Create socket faild!\n"); return -1; } bzero(&my_addr, sizeof(struct sockaddr)); my_addr.sin_family = PF_INET; my_addr.sin_port = htons(5555); my_addr.sin_addr.s_addr = inet_addr("192.168.0.2"); if(bind(sockfd, (struct sockaddr *)&my_addr, sizeof(struct sockaddr)) < 0) { perror("Bind faild!\n"); return -2; } if(listen(sockfd,1) < 0) { perror("Listen error!"); } sockaddr_len = sizeof(struct sockaddr); while(1) { newfd = accept(sockfd,(struct sockaddr *)&their_addr, (socklen_t *)&sockaddr_len); printf("Accept:%s,at ",inet_ntoa(their_addr.sin_addr)); print_date(); if(newfd < 0) { perror("Accept error!\n"); return -3; } /* if(fork() == 0) { printf("Fork() sucessed\n"); close(sockfd); sendtime(newfd); close(newfd); return 0; } */ if((rt = read(newfd, buf, 7)) != 7) { perror("Get date error\n"); continue; } if(!strcmp(buf,"getdate")) { sendtime(newfd); } else { printf("Wrong commands\n"); } close(newfd); } return 0; } int sendtime(int fd) { time_t tm; int rt; tm=time(NULL); rt=write(fd, &tm, sizeof(time_t)); if(rt == sizeof(time_t)) { printf("Send sucessed!\n"); } else { printf("Send error!\n"); } return 0; } void print_date() { time_t tm; time(&tm); printf("%s", ctime(&tm)); } |
**********************************************/
#include
#include
#include
#include
#include
#include
#include
void print_date();
int main(int argc, char **argv)
{
int sockfd;
struct sockaddr_in their_addr;
int newfd;
time_t tm;
int sockaddr_len;
int rt, addr_len;
if(argc != 2) {
perror("Input error\nUsage:client 192.168.0.1\n");
return -1;
}
if((sockfd = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP)) <= 0) {
perror("Create socket faild!\n");
return -2;
}
bzero(&their_addr, sizeof(struct sockaddr_in));
their_addr.sin_family = PF_INET;
their_addr.sin_port = htons(5555);
their_addr.sin_addr.s_addr = inet_addr(argv[1]);
addr_len = sizeof(struct sockaddr);
if(connect(sockfd, (struct sockaddr *)&their_addr, sizeof(struct sockaddr)) < 0) {
perror("Connect faild!\n");
return -3;
}
printf("connected\n");
print_date();
sleep(40);
rt = write(sockfd, "getdate", 8);
rt = read(sockfd,&tm,sizeof(time_t));
if(rt > 0) {
printf("%s\n",ctime(&tm));
}
return 0;
}
void print_date()
{
time_t tm;
time(&tm);
printf("%s\n", ctime(&tm));
}