Socket编程时recv函数错误:Transport endpoint is not connected的解决
Posted wwha
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Socket编程时recv函数错误:Transport endpoint is not connected的解决相关的知识,希望对你有一定的参考价值。
今天在做socket网络通信实验时,server端执行到recv函数处报错:Transport endpoint is not connected。
以下是server和client的源码:
server.c
1 #include <stdio.h> 2 #include <arpa/inet.h> 3 #include <sys/socket.h> 4 #include <string.h> 5 #include <unistd.h> 6 #include <stdlib.h> 7 #define SERVER_PORT 5000 8 9 10 int main(){ 11 /*地址初始化*/ 12 struct sockaddr_in serveraddr; 13 struct sockaddr_in clientaddr; 14 memset(&serveraddr,0,sizeof(serveraddr)); 15 serveraddr.sin_family = AF_INET; 16 serveraddr.sin_addr.s_addr = INADDR_ANY; 17 serveraddr.sin_port = htons(SERVER_PORT); 18 bzero(&(serveraddr.sin_zero),8); 19 //1.create sock 20 int sock,conn,sbind,lis; 21 char buf[32]; 22 sock = socket(AF_INET,SOCK_STREAM,0); 23 if(sock ==-1){perror("sock error");exit(1);} 24 //2.bind 25 sbind = bind(sock, (struct sockaddr*)&serveraddr, sizeof(serveraddr)); 26 if(sock ==-1){perror("bind error");exit(1);} 27 //3.listen 28 lis = listen(sock, 2); 29 if(lis ==-1){perror("listen error");exit(1);} 30 //4.accept 31 int acc,snd,rec; 32 int len = sizeof(struct sockaddr_in); 33 while(1){ 34 acc = accept(sock,(struct sockaddr*)&clientaddr, (socklen_t*)&len); 35 if(acc == -1){ 36 perror("accept error!");continue; 37 } 38 if((rec=recv(sock,buf,1024,0))==-1){perror("server connect failed!");exit(1);}//错误的地方 39 buf[rec]=‘\0‘; 40 if(strcmp(buf,"liu")==0){ 41 snd = send(acc, "Hello,You are connected\n", 24, 0); 42 } 43 } 44 45 close(sock); 46 return 0; 47 }
client.c
#include <stdio.h> #include <arpa/inet.h> #include <sys/types.h> #include <sys/socket.h> #include <unistd.h> #include <string.h> #include <stdlib.h> #define SERVER_PORT 5000 int main(){ /*地址初始化*/ struct sockaddr_in serveraddr; memset(&serveraddr,0,sizeof(serveraddr)); serveraddr.sin_family = AF_INET; serveraddr.sin_addr.s_addr = INADDR_ANY; serveraddr.sin_port = htons(SERVER_PORT); bzero(&(serveraddr.sin_zero),8); //1.create sock int sock,conn; char buf[32]; sock = socket(AF_INET,SOCK_STREAM,0); conn = connect(sock, (struct sockaddr*)&serveraddr, sizeof(serveraddr)); if(conn ==-1){perror("connect error");exit(1);} int snd; snd = send(sock, "liu", 4, 0); if(snd ==-1){perror("send error");exit(1);} int rec; if((rec=recv(sock,buf,1024,0))==-1){perror("client connect failed!");exit(1);} buf[rec]= ‘\0‘; printf("received:%s",buf); close(sock); return 0; }
错误出在recv这个函数。
首先我们来看看accept函数:int accept(int sockfd, void *addr, int *addrlen);
它的返回值是一个客户端的套接字描述符,所以recv和send函数的第一个参数应该填写accept返回的套接字描述符。
所以将server.c中的
if((rec=recv(sock,buf,1024,0))==-1){perror("server connect failed!");exit(1);}
改为:
if((rec=recv(acc,buf,1024,0))==-1){perror("server connect failed!");exit(1);}即可
以上是关于Socket编程时recv函数错误:Transport endpoint is not connected的解决的主要内容,如果未能解决你的问题,请参考以下文章