title: bind failed: Cannot assign requested address
body: <p>I'm trying to write a C program that listens on a port on my machine.
  I'm running into a strange error.</p>
  
  <p>Whenever I try to bind the socket to a fixed ip (either <code>127.0.0.1</code> or my actual IP) I get a <code>"bind failed: Cannot assign requested address"</code> error.
  However when I pass <code>INADDR_ANY</code> to the bind as the address to bind to, it works.</p>
  
  <p>These are the only two IPs I have so it can't be that the 0.0.0.0 works because of some other IP address I have available.</p>
  
  <p>Here is the code:</p>
  
  <pre><code>#include&lt;sys/types.h&gt;
  #include&lt;stdio.h&gt;
  #include&lt;sys/socket.h&gt;
  #include&lt;netinet/in.h&gt;
  #include&lt;errno.h&gt;
  #include&lt;stdlib.h&gt;
  #include&lt;string.h&gt;
  int main()
  {
      int port = 1234;    /* port number */
      int rqst;       /* socket accepting the request */
      socklen_t alen;       /* length of address structure */
      struct sockaddr_in my_addr;    /* address of this service */
      struct sockaddr_in client_addr;  /* client's address */
      int sockoptval = 1;
  
      int svc;
  
  
      /* create a TCP/IP socket */
      if ((svc = socket(AF_INET, SOCK_STREAM, 0)) &lt; 0) {
          perror("cannot create socket");
          exit(1);
      }
  
      /* allow immediate reuse of the port */
      setsockopt(svc, SOL_SOCKET, SO_REUSEADDR, &amp;sockoptval, sizeof(int));
  
      /* bind the socket to our source address */
      memset((char*)&amp;my_addr, 0, sizeof(my_addr));  /* 0 out the structure */
      my_addr.sin_family = AF_INET;   /* address family */
      my_addr.sin_port = htons(port);
      //my_addr.sin_addr.s_addr = htonl(INADDR_ANY); /* Works! */
      my_addr.sin_addr.s_addr = htonl(inet_addr("127.0.0.1")); /* Fails! */
  
      if (bind(svc, (struct sockaddr *)&amp;my_addr, sizeof(my_addr)) &lt; 0) {
          perror("bind failed");
          exit(1);
      }
  
      printf("Listening on %d\n", my_addr.sin_addr.s_addr);
      /* set the socket for listening (queue backlog of 5) */
      if (listen(svc, 5) &lt; 0) {
          perror("listen failed");
          exit(1);
      }
  
      /* loop, accepting connection requests */
      for (;;) {
          while ((rqst = accept(svc, (struct sockaddr *)&amp;client_addr, &amp;alen)) &lt; 0) {
              /* we may break out of accept if the system call */
                          /* was interrupted. In this case, loop back and */
                          /* try again */
                          if ((errno != ECHILD) &amp;&amp; (errno != ERESTART) &amp;&amp; (errno != EINTR)) {
                                  perror("accept failed");
                                  exit(1);
                          }
                  }
          /* the socket for this accepted connection is rqst */
      }
  }
  </code></pre>