- 论坛徽章:
- 0
|
大家好!
我的这个服务器端的socket程序不能接受数据,recv地返回值始终<=0,大家帮我看看哪里出了问题。谢谢啦!
- #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>
- #include<arpa/inet.h>
- # define SERVPORT 1029 /*server listening port*/
- # define BACKLOG 10 /*allow total number of connection*/
- # define MAXBUFLEN 2048
- main()
- {
- int bytesNum;
- char buf[MAXBUFLEN];
- int sockfd,client_fd; /*sock_fd: listening Socket;sock_fd: Data Transfer Socket*/
- struct sockaddr_in my_addr; /*local PC address info*/
- struct sockaddr_in remote_addr; /*remote PC address info */
-
-
- if((sockfd = socket(AF_INET,SOCK_STREAM,0))== -1)
- {
- perror("create Socket Error!");
- exit(1);
- }
-
- bzero(&my_addr,sizeof(my_addr));
- my_addr.sin_family = AF_INET; /*there is a quescstion here:as I have two network card*/
- my_addr.sin_port = htons(SERVPORT);
- my_addr.sin_addr.s_addr = inet_addr("192.168.0.6");/*IP Address Also has a quesstion*/
- // bzero(&(my_addr.sin_zero),8);
- /*
- if(bind(sockfd,(struct sockaddr *)&my_addr,sizeof(my_addr)) == -1)
- {
- //perror("bind Error!");
- printf("bind error is %s\n", strerror(errno));
- exit(1);
- }
- */
- int i_bind_return = bind(sockfd,(struct sockaddr *)&my_addr,sizeof(my_addr));
- printf("bind func return: %d\n", i_bind_return);
-
- if ( i_bind_return == -1 )
- {
- perror("bind error");
- exit(1);
- }
- if(listen(sockfd,BACKLOG) == -1)
- {
- perror("listen Error!");
- exit(1);
- }
- while(1)
- {
- printf("waiting for remote connection \n");
- int sin_size = sizeof(struct sockaddr_in);
- if((client_fd = accept(sockfd,(struct sockaddr *)&remote_addr,&sin_size))==-1)
- {
- perror("accept Error");
- continue;
- }
- // char *s_remote_addr = inet_ntoa(remote_addr.sin_addr);
- printf("received a connection from %s\n",inet_ntoa(remote_addr.sin_addr));
- [b]if(!fork())
- {
- printf("waiting for SN code! \n");
- // if(send(client_fd,"Hello,you are connected!\n",26,0) == -1)
- // {
- // perror("send Error!");
- // }
- do
- {
- memset(buf,0,sizeof(buf));
- /* if((bytesNum = recv (sockfd,buf,MAXBUFLEN,0)) == -1)
- {
- printf("%d \n" ,bytesNum);
- perror("recv Error!");
- }*/
- if((bytesNum = recv (sockfd,buf,MAXBUFLEN,0)) <= 0)
- {
- printf("ending connection!");
- }
- else
- printf("Packet is %s \n",buf);
- }while(bytesNum>0);
- close(client_fd);
- exit(0);
- }
- }
-
- }[/b]
复制代码 |
|