Get formatted message for WSA error codes

百般思念 提交于 2019-12-05 04:23:39

问题


i'm using winsock2 in a win32 c++ application. I would display with MessageBox the network errors that i can retrieve by calling WSAGetLastError(). How can i do this? I saw FormatMessage but i didn't understand how to use it


回答1:


Here's how for example, The following searches error code in the system's message table and places the formatted message in LPTSTR Error buffer.

// Create a reliable, stream socket using TCP.

if ((sockClient = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0)
{
 DWORD err = GetLastError();
 LPTSTR Error = 0;

if(FormatMessage( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
       NULL,
       err,
       0,
       (LPTSTR)&Error,
       0,
       NULL) == 0)
  {
     // Failed in translating the error.
  }
}



回答2:


Hi you can use this code http://www.codeproject.com/KB/tips/formatmessage.aspx




回答3:


In C++11, you can use:

std::system_category().message(WSAGetLastError());

to get your message as a std::string and avoid all that nasty buffer stuff :)

See the function documentation, and this answer that uses it to throw exceptions.



来源:https://stackoverflow.com/questions/4633410/get-formatted-message-for-wsa-error-codes

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