title: socket bind() returns error EINVAL
body: <p>I'm trying to bind the server socket so I can receive and listen for incoming messages from other clients. But I can't bind, it returns error - EINVAL (Invalid Argument). I have gone through the previously asked questions related to this error and Linux manual page says 'The socket is already bound to an address, and the protocol does not support binding to a new address; or the socket has been shut down.'</p>
  
  <p>Here is the problematic server code in c:</p>
  
  <pre><code>#include &lt;stdio.h&gt;
  #include &lt;stdlib.h&gt;
  #include &lt;string.h&gt;
  #include &lt;sys/socket.h&gt;
  #include &lt;unistd.h&gt;
  #include &lt;sys/types.h&gt;
  #include &lt;netinet/in.h&gt;
  
  #define LISTEN_BACKLOG 5
  
  #define handle_error(msg) \
    do { perror(msg); exit(EXIT_FAILURE); } while(0)
  
  int main(int argc, char* argv[])
  {
    int sockfd, cfd;
    struct sockaddr_in myaddr, cl_addr;
    socklen_t cl_len;
    int quit = 0, reuse = 1;
  
    if (argc &lt; 2)
    {
      fprintf(stderr, "ERROR, no port provided\n");
      exit(1);
    }
  
    if ((sockfd = socket(PF_LOCAL, SOCK_STREAM, 0)) == -1)
      handle_error("socket");
  
    printf("socket created.\n");
  
  #ifdef SO_REUSEADDR
    if (setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, (const char*)&amp;reuse, sizeof(reuse)) &lt; 0)
      perror("setsockopt(SO_REUSEADDR) failed");
  #endif
  
  #ifdef SO_REUSEPORT
      if (setsockopt(sockfd, SOL_SOCKET, SO_REUSEPORT, (const char*)&amp;reuse, sizeof(reuse)) &lt; 0)
          perror("setsockopt(SO_REUSEPORT) failed");
  #endif
  
    memset(&amp;myaddr, 0, sizeof(myaddr));
    myaddr.sin_family = AF_INET;
    myaddr.sin_addr.s_addr = htonl(INADDR_ANY);
    myaddr.sin_port = htons(atoi(argv[1]));
  
    printf("portno: %d\n", atoi(argv[1]));
  
    if (bind(sockfd, (struct sockaddr *) &amp;myaddr, sizeof(myaddr)) &lt; 0)
      handle_error("bind");
    printf("bind successful\n");
  
    close(sockfd);
    unlink((const char *) &amp;myaddr);
  
    return 0;
  }
  </code></pre>
  
  <p>When I try to start the server, I get error EINVAL as shown below:</p>
  
  <p>$ ./server 8032</p>
  
  <p>socket created.</p>
  
  <p>portno: 8032</p>
  
  <p>bind: Invalid argument</p>
  
  <p>Will be grateful to receive any inputs on this, thanks!</p>