title: WinSock bind before connects results in WSAEADDRNOTAVAIL - The requested address is not valid in its context
body: <p>I needed to open a socket from a specific local network card using WinSock. I asked about this and got an answer <a href="https://stackoverflow.com/questions/14697963/tcp-ip-connection-on-a-specific-interface">here</a>. In short, the answer advises that you first bind to the local interface, then call connect.</p>
  
  <p>However, when I do this, I get a WSAEADDRNOTAVAIL (10049) "The requested address is not valid in its context.". Why is this? </p>
  
  <p>Assuming the sample code below is part of an application running on the local box 192.168.1.3 and is attempting to connect to remote server 192.168.1.4. I've checked and double-checked that the local and remote addresses are correct. I can ping both ways (from local to remote and remote to local).</p>
  
  <p>I've tried ports other than 0 for the local; no difference. If I remove the bind before the connect, it then works, but I'm then not able to specify a network interface.</p>
  
  <p>So, any idea why I keep getting WSAEADDRNOTAVAIL ? </p>
  
  <pre><code>addrinfo localhints = {0};
  localhints.ai_flags = AI_NUMERICHOST | AI_NUMERICSERV;
  localhints.ai_family = AF_INET;
  localhints.ai_socktype = SOCK_STREAM;
  localhints.ai_protocol = IPPROTO_TCP;
  
  addrinfo *localaddr = NULL;
  getaddrinfo("192.168.1.3", "0", &amp;localhints, &amp;localaddr);
  bind(s, localaddr-&gt;ai_addr, localaddr-&gt;ai_addrlen);
  freeaddrinfo(localaddr);
  
  addrinfo remotehints = {0};
  remotehints.ai_flags = AI_NUMERICHOST | AI_NUMERICSERV;
  remotehints.ai_family = AF_INET;
  remotehints.ai_socktype = SOCK_STREAM;
  remotehints.ai_protocol = IPPROTO_TCP;
  
  addrinfo *remoteaddr = NULL;
  getaddrinfo("192.168.1.4", "12345", &amp;remotehints, &amp;remoteaddr);
  connect(s, remoteaddr-&gt;ai_addr, remoteaddr-&gt;ai_addrlen);
  freeaddrinfo(remoteaddr);
  </code></pre>
  
  <p><strong>EDIT</strong>: This sample code intentionally has no error checking, so that my intent could be communicated in the most efficient way.</p>
  
  <p><strong>EDIT 2</strong>: A bind to 192.168.1.3 causes connect to fail. A bind to 127.0.0.1 works. Yes, I'm 100% sure that 192.168.1.3 is the correct local IP.</p>
  
  <p><strong>EDIT 3</strong>: Right! On a whim, I tried the test app on my home PC and it works fine. So, at least the code does work, and the trouble must be related to my work PC. </p>