Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get formatted message for WSA error codes

Tags:

c++

winsock2

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

like image 722
Stefano Avatar asked Jul 12 '26 07:07

Stefano


2 Answers

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.

like image 179
M. Zoller Avatar answered Jul 13 '26 21:07

M. Zoller


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.
  }
}
like image 22
cpx Avatar answered Jul 13 '26 22:07

cpx



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!