WSAStringToAddress failing

白昼怎懂夜的黑 提交于 2019-12-23 15:30:08

问题


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 :D

EDIT: I discovered using WSAStringToAddressA allowed use of ASCII char instead of tchar


回答1:


WSAStringToAddress() fails with WSAEINVAL when it cannot translate the requested address. A mismatched family value is not the only way that an WSAEINVAL error can occur. As @ChristianStieber stated, you are using a type-cast to pass an 8-bit char[] string literal where a 16-bit wchar_t* pointer is expected. That is just plain wrong. You are passing garbage to WSAStringToAddress(), and it is detecting that.

You need to use the TEXT() macro instead when passing a string literal to an LPTSTR value, eg:

rc = WSAStringToAddress( TEXT("192.168.0.1"), ... );

Otherwise, call the Unicode version of WSAStringToAddress() directly, and put an L prefix in front of the string literal to make it a wchar_t[] instead of a char[], eg:

rc = WSAStringToAddressW( L"192.168.0.1", ... );



回答2:


The examples I've seen online set addrSize to sizeof(struct sockaddr_storage).

There's an example at this link.




回答3:


In my opinion, this comment doesn't say it's the only possible reason for this error.

In particular, this line strikes me:

(LPWSTR) "192.168.0.1",

You are taking an 8-bit string and just casting it to the wide version. Did you try using L"192...."?



来源:https://stackoverflow.com/questions/11694312/wsastringtoaddress-failing

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!