C语言 如何从 WSAGetLastError() 检索错误字符串?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3400922/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 06:04:58  来源:igfitidea点击:

How do I retrieve an error string from WSAGetLastError()?

cwinapisocketswinsock

提问by Drew Hall

I'm porting some sockets code from Linux to Windows.

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

In Linux, I could use strerror()to convert an errno code into a human-readable string.

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

MSDN documentation shows equivalent strings for each error code returned from WSAGetLastError(), but I don't see anything about how to retrieve those strings. Will strerror()work here too?

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

How can I retrieve human-readable error strings from Winsock?

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

采纳答案by CB Bailey

As the documentation for WSAGetLastErrorsays you can use FormatMessageto obtain a text version of the error message.

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

You need to set FORMAT_MESSAGE_FROM_SYSTEMin the dwFlagsparameter and pass the error code as the dwMessageparameter.

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

回答by mxcl

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

回答by Stan Sieler

A slightly simpler version of mxcl's answer, which removes the need for malloc/free and the risks implicit therein, and which handles the case where no message text is available (since Microsoft doesn't document what happens then):

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

int
   err;

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


msgbuf [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