本文介绍了WSAStringToAddress失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图使用以下C ++代码从IPv4字符串地址填充sockaddr_in结构:

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 );
}

它失败,错误代码10022,即WSAEINVAL。在它说明,当sockaddr_in的地址系列未设置为AF_INET或AF_INET6时,会发生此错误代码我已经清楚地做了。

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.

我在Windows Server 2008 R2 SP1上运行Visual C ++ 2008 Express Edition,但是我不使用较新的地址转换函数,因为我需要向后兼容Windows XP / Windows Server 2000以上。

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.

有谁知道如何解决这个问题/我的代码有什么问题?您可以给任何解决方案:D

Does anyone know how to solve this problem/what is wrong with my code? Any solutions you can give are appreciated :D

编辑:
我发现使用WSAStringToAddressA允许使用ASCII字符代替tchar

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

推荐答案

WSASEINVAL 时,WSAStringToAddress()它不能翻译请求的地址。不匹配的系列值不是发生 WSAEINVAL 错误的唯一方法。如@ChristianStieber所说,你使用一个类型转换来传递一个8位的 char [] 字符串文字,其中16位 wchar_t * / code>指针。这只是平淡的错误。你传递垃圾到 WSAStringToAddress(),它正在检测

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.

你需要使用<$当将字符串文字传递给 LPTSTR 值时,c $ c> TEXT()宏,例如:

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"), ... );

否则,调用Unicode版本 WSAStringToAddress()直接,并在字符串字面前放置一个 L 前缀,使它成为一个 wchar_t [] 例如:

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", ... );

这篇关于WSAStringToAddress失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-19 07:27