I’m trying to populate a sockaddr_in structure from an IPv4 string address using the following C++ code:
// WSAStringToAddress
struct sockaddr_in sock;
int addrSize = sizeof( struct sockaddr_in );
memset( &sock, 0, addrSize );
sock.sin_family = AF_INET;
rc = WSAStringToAddress( (LPWSTR) "192.168.0.1",
AF_INET,
NULL,
(LPSOCKADDR) &sock,
&addrSize );
if ( rc != 0 )
{
rc = WSAGetLastError();
printf( "WSAStringToAddress: error=[%d]\n", rc );
}
It is failing with error code 10022, which is WSAEINVAL. On http://msdn.microsoft.com/en-us/library/windows/desktop/ms742214%28v=vs.85%29.aspx it states this error code occurs when the address family of sockaddr_in is not set to AF_INET or AF_INET6, which I have clearly done.
I’m running Visual C++ 2008 Express Edition on Windows Server 2008 R2 SP1, but I’m not using the newer address conversion functions as I need backwards compatibility from Windows XP/Windows Server 2000 onwards.
Does anyone know how to solve this problem/what is wrong with my code? Any solutions you can give are appreciated 😀
EDIT:
I discovered using WSAStringToAddressA allowed use of ASCII char instead of tchar
WSAStringToAddress()fails withWSAEINVALwhen it cannot translate the requested address. A mismatched family value is not the only way that anWSAEINVALerror can occur. As @ChristianStieber stated, you are using a type-cast to pass an 8-bitchar[]string literal where a 16-bitwchar_t*pointer is expected. That is just plain wrong. You are passing garbage toWSAStringToAddress(), and it is detecting that.You need to use the
TEXT()macro instead when passing a string literal to anLPTSTRvalue, eg:Otherwise, call the Unicode version of
WSAStringToAddress()directly, and put anLprefix in front of the string literal to make it awchar_t[]instead of achar[], eg: