title: Binding socket to computer's address for listening
body: <p>I've created code designed to bind a new socket to the computer's addresses for listening for incoming connections on a specific port. I'm using getaddrinfo. Is this the best way? It seems pointless converting the port integer to a string. Is there a way to do this with no need for sprintf?</p>
  
  <pre><code>bool CBSocketBind(void * socketID,u_int16_t port){
      struct addrinfo hints,*res,*ptr;
      int socketIDInt;
      // Set hints for the computer's addresses.
      memset(&amp;hints, 0, sizeof(hints));
      hints.ai_flags = AI_PASSIVE;
      hints.ai_family = AF_UNSPEC;
      hints.ai_socktype = SOCK_STREAM;
      // Get host for listening
      char portStr[6];
      sprintf(portStr, "%u",port);
      if (getaddrinfo(NULL, portStr, &amp;hints, &amp;res) != 0)
          return false;
      // Attempt to bind to one of the addresses.
      for(ptr = res; ptr != NULL; ptr = ptr-&gt;ai_next) {
          if ((socketIDInt = socket(ptr-&gt;ai_family, ptr-&gt;ai_socktype,ptr-&gt;ai_protocol)) == -1)
              continue;
          if (bind(socketIDInt, ptr-&gt;ai_addr, ptr-&gt;ai_addrlen) == -1) {
              close(socketIDInt);
              continue;
          }
          break; // Success.
      }
      freeaddrinfo(res);
      if (ptr == NULL) // Failure
          return false;
      socketID = malloc(sizeof(int));
      *(int *)socketID = socketIDInt; // Set socket ID
      // Make socket non-blocking
      fcntl(socketIDInt,F_SETFL,fcntl(socketIDInt,F_GETFL,0) | O_NONBLOCK);
      return true;
  }
  </code></pre>