分类: LINUX
2013-05-29 12:55:13
原文地址:linux socket的bug?? 作者:playmud
/********************************************** 作者:猪头流氓 时间: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)); } |
/********************************************** perror("Create socket faild!\n"); perror("Connect faild!\n"); close(sockfd); } |