socket相关函数一直出错,检查和上网搜索后,得不到解决

发布于 2019-08-14 23:44:57


bind函数
resocket函数
listen函数
不知道为什么一直返回fail。麻烦看一下是怎么回事
、、、
void tryconnect(void)
{

     if(demo_sock_s->server_fd != -1)
  {          
  closesocket(demo_sock_s->server_fd);
        }
    reconnect();      

}
void reconnect(void)
{

int new_fd;
int recvbytes;
int yes = 1;
int ret;

char sendBuf[100];
   char recvBuf[100];

fd_set fdsr;

struct tls_socket_desc skd;
struct sockaddr_in server_addr;
struct sockaddr_in client_addr;
socklen_t sin_size;
demo_sock_s->my_port = 1020;
//创建socket端口TCP
demo_sock_s->server_fd = socket(AF_INET,SOCK_STREAM,0);
if (demo_sock_s->server_fd == -1)
{
    printf("%s\n","socket创建出错!");
    
}

if (setsockopt(demo_sock_s->server_fd, SOL_SOCKET, SO_REUSEADDR, &yes,
         sizeof(int)) == -1)
   {
    
       printf("set sockopt err\n");
    
   }
   demo_sock_s->my_port = 1020;
server_addr.sin_addr.s_addr = INADDR_ANY;
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(demo_sock_s->my_port);
memset(server_addr.sin_zero, '\0', sizeof(server_addr.sin_zero));

ret = bind(demo_sock_s->server_fd,(struct sockaddr *)&server_addr,sizeof(server_addr));

if( ret == 0)
{
   printf("%s\n","bind success");
    
} else
{
   printf("%s\n","bind fail");
     tryconnect();
}

   ret = listen(demo_sock_s->server_fd, BACKLOG);
if (ret == -1) 
{
    printf("%s\n","listen出错!");
    tryconnect();
}

printf("listen port %d\n", demo_sock_s->my_port);

demo_sock_s->conn_num = 0;
sin_size = sizeof(client_addr);

if (connect(demo_sock_s->server_fd, (struct sockaddr *)&server_addr,sizeof(struct sockaddr)) == -1) 
{
    printf("%s\n","connect出错!");
}

if ((recvbytes=recv(demo_sock_s->server_fd, recvBuf, 100, 0)) == -1) 
{
    printf("%s\n","recv出错!");
    
}

  while(1)
  {
          
    FD_ZERO(&fdsr);
    FD_SET(demo_sock_s->server_fd, &fdsr);
        
    ret = select(demo_sock_s->server_fd + 1, &fdsr, NULL, NULL, NULL);
    if(ret == -1)
    {
        printf("%s\n","select error");
        tryconnect();
    }else
    {
        if (FD_ISSET(demo_sock_s->server_fd, &fdsr))
        {
            
          new_fd= accept(demo_sock_s->server_fd,(struct sockaddr *)&client_addr,&sin_size);
          printf("accept newfd=%d\n",new_fd);
             
            if (new_fd <= 0)
             {
              printf("accept err\n");
             continue;
             }
           printf("client_addr = %s,port:%d",inet_ntoa(client_addr),ntohs(client_addr.sin_port));  
            recv(demo_sock_s->server_fd,recvBuf,100,0);
          printf("%s\n",recvBuf);
        }
        closesocket(demo_sock_s->server_fd);
    }
   }

}
void main(void)
{
reconnect();
}

查看更多

关注者
0
被浏览
52
0 个回答
暂无答案,快来添加答案吧

撰写答案

请登录后再发布答案,点击登录

发布
问题

分享
好友

手机
浏览

扫码手机浏览