How do I retrieve an error string from WSAGetLastError()?

后端 未结 3 945
猫巷女王i
猫巷女王i 2020-12-16 09:59

I\'m porting some sockets code from Linux to Windows.

In Linux, I could use strerror() to convert an errno code into a human-readable string.

MS

3条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-16 10:35

    A slightly simpler version of mxcl's answer, which removes the need for malloc/free and the risks implicit therein, and which handles the case where no message text is available (since Microsoft doesn't document what happens then):

    int
       err;
    
    char
       msgbuf [256];   // for a message up to 255 bytes.
    
    
    msgbuf [0] = '\0';    // Microsoft doesn't guarantee this on man page.
    
    err = WSAGetLastError ();
    
    FormatMessage (FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,   // flags
                   NULL,                // lpsource
                   err,                 // message id
                   MAKELANGID (LANG_NEUTRAL, SUBLANG_DEFAULT),    // languageid
                   msgbuf,              // output buffer
                   sizeof (msgbuf),     // size of msgbuf, bytes
                   NULL);               // va_list of arguments
    
    if (! *msgbuf)
       sprintf (msgbuf, "%d", err);  // provide error # if no string available
    

提交回复
热议问题