|
楼主 |
发表于 2005-5-22 17:58:24
|
显示全部楼层
谢谢斑竹!!
这是代码:
- #include <stdio.h>
- #include <stdlib.h>
- #include <errno.h>
- #include <string.h>
- #include <sys/types.h>
- #include <netinet/in.h>
- #include <sys/socket.h>
- #include <sys/wait.h>
- #define MYPORT 4000
- #define BACKLOG 10
- main()
- {
- int sockfd, new_fd; /* listen on sock_fd, new connection on new_fd
- */
- struct sockaddr_in my_addr; /* my address information */
- struct sockaddr_in their_addr; /* connector's address information */
- int sin_size,len;
- char buf[16384];
- if ((sockfd=socket(AF_INET,SOCK_STREAM,0))==-1){
- perror("call to socket");
- exit(1);
- }
-
- my_addr.sin_family = AF_INET ; /*host byte order*/
- my_addr.sin_port = htons(MYPORT);/* short,network byte order*/
- my_addr.sin_addr.s_addr =INADDR_ANY; /* auto-fill with my IP*/
- bzero(&(my_addr.sin_zero),sizeof(struct sockaddr_in));/*zero the rest of the struct*/
- if(bin(sockfd,(struct sockaddr *)&my_addr,sizeof(struct sockaddr))==-1){
- perror("call to bind");
- exit(1);
- }
- if(listen(sockfd,BACKLOG)==-1){
- perror("call to listen ");
- exit(1);
- }
-
- printf("Accepting connection...\n");
- while(1) {/*main accept() loop*/
- sin_size=sizeof(struct sockaddr_in);
- if((new_fd = accept(sockfd,(struct sockaddr *)&their_addr,&sin_size)) ==-1){
- perror("call to accept");
- continue; /*why not exit(1)???*/
- }
-
- if (!fork()){ /*child process*/
- if (recv(new_fd,buf,16384,0)==-1){
- perror("call to recv");
- exit(1);
- }
-
- printf("Received form client:%s/n",buf);
-
- len=strlen(buf);
- //buf[len]="\n";
-
- if (send(new_fd,buf,len,0)==-1){
- perror("call to send");
- exit(1);
- }
- close(new_fd);
- exit(0);
- }
- close(new_fd);/*??*/
- while(waitpid(-1,NULL,WNOHANG)>0);/* clean up child processes*/
- }
- }
复制代码
编译的时候就是gcc -o,我是初学者,请大家帮忙看看,谢谢 |
|