ConnectEx requires the socket to be "initially bound", but to what?
connect does this step automatically, but ConnectEx does not.
Correct.
Is my assessment correct?
Yes.
Is there a way to do this automatic bind that is agnostic to the address family, or will I have to handle each of AF_INET, AF_INET6, AF_BTH (Bluetooth), etc. manually?
I believe that INADDR_ANY
is a bunch of zeros in all address families, so you could just try using the memset()
and omitting the assignment to addr.sin_addr.s_addr
completely. Whether this is kosher, portable, politically correct etc. is another question into which I will not enter.
It seems pretty curious that Microsoft didn't manage to have ConnectEx()
call bind()
internally, considering that saving system calls is the motivation for its existence, and also considering that most programs never bind an outbound socket at all.
It is possible to get the bind address for ConnectEx in an address family independent way.
Solution 1
Call getaddrinfo
with the following options:
pServiceName = "0"hints.ai_flags = AI_PASSIVEhints.ai_family = address family of the socket
Then use the first result of the returned address list.
To get the address family of the socket you can use getsockopt
with SO_PROTOCOL_INFOW
.
Solution 2
Use SOCKADDR_STORAGE
for the address structure and call INETADDR_SETANY
which is defined in MSTcpIP.h
. It supports AF_INET
and AF_INET6
.