title: C - Create a sockaddr struct
body: <p>I am trying to create a <code>void mksockaddr(int af, int proto, char addr[], struct sockaddr* dst)</code> that creates a sockaddr structure, here's what I've done:</p>
  
  <pre><code>void sockaddr(int af, int port, char addr[], struct sockaddr* dst) {
    if (af == AF_INET) {
      struct sockaddr_in s;
      s.sin_family = af;
      s.sin_port = htons(port);
      inet_pton(af, addr, &amp;s.sin_addr);
      memcpy(dst, &amp;s, sizeof(s));
    } else {
      struct sockaddr_in6 s;
      s.sin6_family = af;
      s.sin6_port = htons(port);
      s.sin6_flowinfo = 0;
      inet_pton(af, addr, &amp;s.sin6_addr);
      memcpy(dst, &amp;s, sizeof(s));
    }
  }
  </code></pre>
  
  <p>This seems to be no problem with AF_INET (IPv4), I can <code>bind()</code> without any problem, but when I try to use AF_INET6, <code>bind()</code> give me Invalid argument.</p>
  
  <p>Here's the code I use to <code>bind()</code>:</p>
  
  <pre><code>int sock_fd = socket(AF_INET6, SOCK_RAW, proto);
  struct sockaddr sin;
  sockaddr(AF_INET6, proto, src, &amp;sin);
  if(bind(sock_fd, &amp;sin, sizeof(sin)) &lt; 0) {
    fprintf(stderr, "[ERR] can't bind socket: %s\n", strerror(errno));
    exit(1);
  } // got Invalid argument
  </code></pre>
  
  <p>However, I can <code>bind()</code> just fine if I construct a <code>sockaddr_in6</code> myself: </p>
  
  <pre><code>struct sockaddr_in6 sin;
  sin.sin6_port = htons(proto);
  sin.sin6_family = AF_INET6;
  inet_pton(AF_INET6, src, &amp;sin.sin6_addr);
  if(bind(sock_fd, (struct sockaddr*) &amp;sin, sizeof(sin)) &lt; 0) {
    fprintf(stderr, "[ERR] can't bind socket.\n");
    exit(1);
  } // work just fine
  </code></pre>
  
  <p>So I cast the <code>sockaddr</code> created by the function back to <code>sockaddr_in6</code>, and I can see that all the fields are same except <code>sin6_scope_id</code>. To my understanding, <code>sin6_scope_id</code> does not matter unless I'm dealing with a link-local IPv6 address.</p>
  
  <p>Am I missing anything here?</p>