开发者

Get formatted message for WSA error codes

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 i开发者_JAVA技巧t


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.
  }
}


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.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜