如何从WSAGetLastError()中检索错误字符串?
我正在将一些套接字代码从Linux移植到Windows。
在Linux中,我可以使用strerror()
将errno代码转换为人类可读的字符串。
MSDN文档显示了从WSAGetLastError()
返回的每个错误代码的等效字符串,但我没有看到有关如何检索这些字符串的任何信息。 strerror()
也会在这里工作吗?
如何从Winsock中检索人类可读的错误字符串?
正如WSAGetLastError
的文档所述,您可以使用FormatMessage
获取错误消息的文本版本。
您需要在dwFlags
参数中设置FORMAT_MESSAGE_FROM_SYSTEM
并将错误代码作为dwMessage
参数传递。
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);
一个稍微简单的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