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
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.
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.
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With