Unix C socket server not accepting connections

不羁岁月 提交于 2019-12-06 00:03:27

Are you really trying to listen on port zero? Try a high port number, preferably > 1024. /etc/services will give a hint about free ports - but it only a set of comments, those port numbers are not enforced.

Edit: another hint. The port number should be in network order, so the assignment should use htons(). It could be that the "random numbers" you are getting are simple numbers that appear garbled because you might be on a little-endian machine (like Intel). When you print them, convert them back using ntohs().

props to @askmish for inspiring this one

    //Print port
    printf("%i", serv_addr.sin_port);

becomes

    //Print port
    printf("%i", htons(serv_addr.sin_port));

In your code:

  • Instead of:

    serv_addr.sin_port = 0;
    

    try this:

    serv_addr.sin_port=htons(2056);//Any port no. 
    
  • Instead of:

     listen(sock_fd,32);
    

    try this:

     if(listen(sock_fd,SOMAXCONN)<0)//Just to be sure that you are considering max. no. of requests
     {  fprintf(stderr,"error with listen");
        exit(1);}
    
  • Also for:

     conn_fd = accept(sock_fd,(struct sockaddr*)&cli_addr,clilen);
    

    Add this:

     if(conn_fd <0)
     {
       //handle the error here
     }
    

If none of these solve your issues, then, there might be problem with the client code or your server environment.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!