title: How to re bind a udp socket in Linux
body: <p>I am an experienced Linux socket programmer and am writing a server application which has many outgoing interfaces. Now server socket binds to a random source port in the start of the process along with INADDR_ANY.</p>
  
  <p>Later at some point when submitting response to a specific node, i need to assign a fixed <em>source ip address</em>. The standard way to do this is calling bind. However, bind is called once for the port number, <strong>successive calls fail with invalid argument error.</strong></p>
  
  <p>Creating a new socket is not really a good choice since i will have to be doing this very often upon responding to some clients.</p>
  
  <p>I have also explored SO and a lot of socket options such as IP_FREEBIND, but it doesn't quite suite my scenario.</p>
  
  <p>Perhaps using IP_PKT_INFO and setting source address might work unless it suffers the same problem i.e. not allowing a socket once bound to INADDRANY to rebind to a fixed source ip latter.</p>
  
  <p><em>Is there a way to unbind an existing socket or an alternate way to setting source ip address in outgoing packet?</em></p>
  
  <pre><code>    int sock = socket(AF_INET, SOCK_DGRAM, 0);
  
      if(sock &lt; 0)
          printf("Failed creating socket\n");
  
      struct sockaddr_in addr;
      memset(&amp;addr, 0, sizeof(struct sockaddr_in));
      addr.sin_family = AF_INET;
      addr.sin_port = htons(1500);
      addr.sin_addr.s_addr = INADDR_ANY;
  
      // first bind succeeds
      if ( (status = bind(sock, (struct sockaddr *) &amp;addr, sizeof(addr))) &lt; 0)
          printf("bind error with port %s\n", strerror(errno));  
  
      struct sockaddr_in src_addr;
      memset(&amp;src_addr, 0, sizeof(struct sockaddr_in));
      src_addr.sin_family = AF_INET;
      if (inet_aton("10.0.2.17", &amp;(src_addr.sin_addr)) == 0)
          printf("Failed copying address\n");
  
      // second bind fails
      if((status = bind(sock, (struct sockaddr *)&amp;src_addr, sizeof(src_addr))) &lt; 0)
          printf("re bind error with ip %s\n", strerror(errno));
  </code></pre>
  
  <p>Any ideas in this regard will be highly appreciated. I have gone through considerable material on sockets, SO etc. but no success yet.</p>