如何从WSAGetLastError()中检索错误字符串?

Dre*_*all 26 c sockets winapi winsock

我正在将一些套接字代码从Linux移植到Windows.

在Linux中,我可以使用strerror()将errno代码转换为人类可读的字符串.

MSDN文档显示返回的每个错误代码的等效字符串WSAGetLastError(),但我没有看到有关如何检索这些字符串的任何信息.会strerror()在这里工作吗?

如何从Winsock中检索人类可读的错误字符串?

mxc*_*xcl 36

wchar_t *s = NULL;
FormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, 
               NULL, WSAGetLastError(),
               MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
               (LPWSTR)&s, 0, NULL);
fprintf(stderr, "%S\n", s);
LocalFree(s);
Run Code Online (Sandbox Code Playgroud)

  • 这里的`&s`参数必须被转换为LPTSTR,因为这个函数在这里使用了一个hack,这个参数返回一个指向string的字符串作为字符串. (3认同)

CB *_*ley 16

正如文档所述,WSAGetLastError您可以使用它FormatMessage来获取错误消息的文本版本.

您需要FORMAT_MESSAGE_FROM_SYSTEMdwFlags参数中设置并将错误代码作为dwMessage参数传递.


Sta*_*ler 5

mxcl答案的稍简单版本,它消除了对malloc / free的需求以及其中所隐含的风险,并且可以处理没有可用消息文本的情况(因为Microsoft并未记录随后发生的情况):

int
   err;

char
   msgbuf [256];   // for a message up to 255 bytes.


msgbuf [0] = '\0';    // Microsoft doesn't guarantee this on man page.

err = WSAGetLastError ();

FormatMessage (FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,   // flags
               NULL,                // lpsource
               err,                 // message id
               MAKELANGID (LANG_NEUTRAL, SUBLANG_DEFAULT),    // languageid
               msgbuf,              // output buffer
               sizeof (msgbuf),     // size of msgbuf, bytes
               NULL);               // va_list of arguments

if (! *msgbuf)
   sprintf (msgbuf, "%d", err);  // provide error # if no string available
Run Code Online (Sandbox Code Playgroud)