I needed to open a socket from a specific local network card using WinSock. I asked about this and got an answer here. In short, the answer advises that you first bind to the local interface, then call connect.
However, when I do this, I get a WSAEADDRNOTAVAIL (10049) "The requested address is not valid in its context.". Why is this?
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).
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.
So, any idea why I keep getting WSAEADDRNOTAVAIL ?
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", &localhints, &localaddr);
bind(s, localaddr->ai_addr, localaddr->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", &remotehints, &remoteaddr);
connect(s, remoteaddr->ai_addr, remoteaddr->ai_addrlen);
freeaddrinfo(remoteaddr);
EDIT: This sample code intentionally has no error checking, so that my intent could be communicated in the most efficient way.
EDIT 2: 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.
EDIT 3: 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.