title: C Server Sockets - bind() error
body: <p>Everything compiles without errors and warnings. I start the program. I visit localhost:8080 and the program stops - great. I try to run the program again and I get <em>Error: unable to bind</em> message. <strong>Why?</strong></p>
  
  <p><strong>Code:</strong></p>
  
  <pre><code>#include &lt;sys/types.h&gt;
  #include &lt;sys/socket.h&gt;
  #include &lt;netinet/in.h&gt;
  #include &lt;arpa/inet.h&gt;
  
  #include &lt;errno.h&gt;
  
  #include &lt;stdio.h&gt;
  #include &lt;stdlib.h&gt;
  #include &lt;string.h&gt;
  
  #define PORT 8080
  #define PROTOCOL 0
  #define BACKLOG 10
  
  int main()
  {
    int fd;
    int connfd;
  
    struct sockaddr_in addr; // For bind()
    struct sockaddr_in cliaddr; // For accept()
    socklen_t cliaddrlen = sizeof(cliaddr);
  
    // Open a socket
    fd = socket(AF_INET, SOCK_STREAM, PROTOCOL);
    if (fd == -1) {
      printf("Error: unable to open a socket\n");
      exit(1);
    }
  
    // Create an address
    //memset(&amp;addr, 0, sizeof addr);
    addr.sin_addr.s_addr = INADDR_ANY;
    addr.sin_family = AF_INET;
    addr.sin_port = htons(PORT);
  
    if ((bind(fd, (struct sockaddr *)&amp;addr, sizeof(addr))) == -1) {
      printf("Error: unable to bind\n");
      printf("Error code: %d\n", errno);
      exit(1);
    }
  
    // List for connections
    if ((listen(fd, BACKLOG)) == -1) {
      printf("Error: unable to listen for connections\n");
      printf("Error code: %d\n", errno);
      exit(1);
    }
  
    // Accept connections
    connfd = accept(fd, (struct sockaddr *) &amp;cliaddr, &amp;cliaddrlen);
    if (connfd == -1) {
      printf("Error: unable to accept connections\n");
      printf("Error code: %d\n", errno);
      exit(1);
    }
  
    //read(connfd, buffer, bufferlen);
    //write(connfd, data, datalen);
    //  close(connfd);
  
    return 0;
  }
  </code></pre>