2

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

Stefano
  • 3,213
  • 9
  • 60
  • 101

3 Answers3

4

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.
  }
}
cpx
  • 17,009
  • 20
  • 87
  • 142
  • it works but i have two questions: why should i cast &Error to LPTSTR when I can simply write Error? And should i deallocate memory with LocalFree(Error)? – Stefano Jan 08 '11 at 11:08
  • Because then you would be passing the address of pointer (which expects a type of pointer to pointer) to another pointer and since `FORMAT_MESSAGE_ALLOCATE_BUFFER` flag is supposed to allocate buffer for message which would be pointed by `LPSTR Error`. You must free the memory when it is no longer needed. – cpx Jan 08 '11 at 13:20
  • New applications should use [`HeapFree()`](https://msdn.microsoft.com/en-us/library/aa366701(v=vs.85).aspx) instead of `LocalFree()`. In this case you want `HeapFree(GetProcessHeap(), 0, Error)`. https://msdn.microsoft.com/en-us/library/aa366596(v=vs.85).aspx – Tim Nov 21 '16 at 23:48
2

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.

M. Zoller
  • 65
  • 9
1

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

Sanja Melnichuk
  • 3,465
  • 3
  • 25
  • 46