title: When is the UDP source port set?
body: <p>I'm writing a very small C UDP client. I know that a random port is chosen as source port when you send data to the server. I also know that you can use bind to specify yourself the port you want a response.</p>
  
  <p>However, I don't know when is the port randomly chosen? For example, I would like to rely on the sender address to keep track of users. It currently works only if the client does not shutdown, the port is still the same then a simple memcmp is enough to detect the same client.</p>
  
  <p>This small code will use the same source port until it exits:</p>
  
  <pre><code>#include &lt;sys/types.h&gt;
  #include &lt;sys/socket.h&gt;
  #include &lt;netinet/in.h&gt;
  #include &lt;netdb.h&gt;
  #include &lt;stdio.h&gt;
  #include &lt;stdlib.h&gt;
  #include &lt;string.h&gt;
  #include &lt;err.h&gt;
  
  int main(void)
  {
      int s, error, ch;
      struct addrinfo hints, *res;
  
      memset(&amp;hints, 0, sizeof (struct addrinfo));
      hints.ai_family = AF_INET;
      hints.ai_socktype = SOCK_DGRAM;
  
      if ((error = getaddrinfo("localhost", "9988", &amp;hints, &amp;res)))
              errx(1, "%s", gai_strerror(error));
  
      if ((s = socket(res-&gt;ai_family, res-&gt;ai_socktype, 0)) &lt; 0)
              err(1, "socket");
  
      while ((ch = fgetc(stdin)) != EOF)
              sendto(s, &amp;ch, 1, 0, res-&gt;ai_addr, res-&gt;ai_addrlen);
  }
  </code></pre>
  
  <p>And running something like : dmesg | ./client will use the same address until the program exits. However, when you run it again, the port is different.</p>
  
  <p>So is it the socket function that choose a port? Or the system? Is it sure that the port will still be the same during the client lifetime?</p>