WSAGetLastError function (winsock.h)
The WSAGetLastError function returns the error status for the last Windows Sockets operation that failed.
Syntax
Return value
The return value indicates the error code for this thread’s last Windows Sockets operation that failed.
Remarks
The WSAGetLastError function returns the last error that occurred for the calling thread. When a particular Windows Sockets function indicates an error has occurred, this function should be called immediately to retrieve the extended error code for the failing function call. This extended error code can be different from the error code obtained from getsockopt when called with an optname parameter of SO_ERROR, which is socket-specific since WSAGetLastError is for all thread-specific sockets.
If a function call’s return value indicates that error or other relevant data was returned in the error code, WSAGetLastError should be called immediately. This is necessary because some functions may reset the last extended error code to 0 if they succeed, overwriting the extended error code returned by a previously failed function. To specifically reset the extended error code, use the WSASetLastError function call with the iError parameter set to zero. A getsockopt function when called with an optname parameter of SO_ERROR also resets the extended error code to zero.
The WSAGetLastError function should not be used to check for an extended error value on receipt of an asynchronous message. In this case, the extended error value is passed in the lParam parameter of the message, and this can differ from the value returned by WSAGetLastError.
The Windows Sockets extended error codes returned by this function and the text description of the error are listed under Windows Sockets Error Codes. These error codes and a short text description associated with an error code are defined in the Winerror.h header file. The FormatMessage function can be used to obtain the message string for the returned error.
For information on how to handle error codes when porting socket applications to Winsock, see Error Codes — errno, h_errno and WSAGetLastError.
WindowsВ PhoneВ 8: This function is supported for Windows Phone Store apps on WindowsВ PhoneВ 8 and later.
WindowsВ 8.1 and Windows ServerВ 2012В R2: This function is supported for Windows Store apps on WindowsВ 8.1, Windows ServerВ 2012В R2, and later.
WSAGetLastError function (winsock2.h)
The WSAGetLastError function returns the error status for the last Windows Sockets operation that failed.
Syntax
Return value
The return value indicates the error code for this thread’s last Windows Sockets operation that failed.
Remarks
The WSAGetLastError function returns the last error that occurred for the calling thread. When a particular Windows Sockets function indicates an error has occurred, this function should be called immediately to retrieve the extended error code for the failing function call. This extended error code can be different from the error code obtained from getsockopt when called with an optname parameter of SO_ERROR, which is socket-specific since WSAGetLastError is for all thread-specific sockets.
If a function call’s return value indicates that error or other relevant data was returned in the error code, WSAGetLastError should be called immediately. This is necessary because some functions may reset the last extended error code to 0 if they succeed, overwriting the extended error code returned by a previously failed function. To specifically reset the extended error code, use the WSASetLastError function call with the iError parameter set to zero. A getsockopt function when called with an optname parameter of SO_ERROR also resets the extended error code to zero.
The WSAGetLastError function should not be used to check for an extended error value on receipt of an asynchronous message. In this case, the extended error value is passed in the lParam parameter of the message, and this can differ from the value returned by WSAGetLastError.
The Windows Sockets extended error codes returned by this function and the text description of the error are listed under Windows Sockets Error Codes. These error codes and a short text description associated with an error code are defined in the Winerror.h header file. The FormatMessage function can be used to obtain the message string for the returned error.
For information on how to handle error codes when porting socket applications to Winsock, see Error Codes — errno, h_errno and WSAGetLastError.
WindowsВ PhoneВ 8: This function is supported for Windows Phone Store apps on WindowsВ PhoneВ 8 and later.
WindowsВ 8.1 and Windows ServerВ 2012В R2: This function is supported for Windows Store apps on WindowsВ 8.1, Windows ServerВ 2012В R2, and later.
Error Codes — errno, h_errno and WSAGetLastError
In Winsock applications, error codes are retrieved using the WSAGetLastError function, the Windows Sockets substitute for the Windows GetLastError function. The error codes returned by Windows Sockets are similar to UNIX socket error code constants, but the constants are all prefixed with WSA. So in Winsock applications the WSAEWOULDBLOCK error code would be returned, while in UNIX applications the EWOULDBLOCK error code would be returned.
Error codes set by Windows Sockets are not made available through the errno variable. Additionally, for the getXbyY class of functions, error codes are not made available through the h_errno variable. The WSAGetLastError function is intended to provide a reliable way for a thread in a multithreaded process to obtain per-thread error information.
For compatibility with Berkeley UNIX (BSD), early versions of Windows (WindowsВ 95 with the Windows SocketВ 2 Update and WindowsВ 98, for example) redefined regular Berkeley error constants typically found in errno.h on BSD as the equivalent Windows Sockets WSA errors. So for example, ECONNREFUSED was defined as WSAECONNREFUSED in the Winsock.h header file. In subsequent versions of Windows (WindowsВ NT 3.1 and later) these defines were commented out to avoid conflicts with errno.h used with Microsoft C/C++ and Visual Studio.
The Winsock2.h header file included with the Microsoft Windows Software Development Kit (SDK), Platform Software Development Kit (SDK), and Visual Studio still contains a commented out block of defines within an #ifdef 0 and #endif block that define the BSD socket error codes to be the same as the WSA error constants. These can be used to provide some compatibility with UNIX, BSD, and Linux socket programming. For compatibility with BSD, an application may choose to change the Winsock2.h and uncomment this block. However, application developers are strongly discouraged from uncommenting this block because of inevitable conflicts with errno.h in most applications. Also, the BSD socket errors are defined to very different values than are used in UNIX, BSD, and Linux programs. Application developers are very strongly encouraged to use the WSA error constants in socket applications.
These defines remain commented out in the Winsock2.h header within an #ifdef 0 and #endif block. If an application developer insists on using the BSD error codes for compatibility, then an application may choose to include a line of the form:
This allows networking code which was written to use the global errno to work correctly in a single-threaded environment. There are some very serious drawbacks. If a source file includes code which inspects errno for both socket and non-socket functions, this mechanism cannot be used. Furthermore, it is not possible for an application to assign a new value to errno. (In Windows Sockets, the function WSASetLastError may be used for this purpose.)
Typical BSD Style
Although error constants consistent with Berkeley Sockets 4.3 are provided for compatibility purposes, applications are strongly encouraged to use the WSA error code definitions. This is because error codes returned by certain Windows Sockets functions fall into the standard range of error codes as defined by Microsoft CВ©. Thus, a better version of the preceding source code fragment is:
The original Winsock 1.1 specification defined in 1995 recommended a set of error codes, and listed the possible errors that can be returned as a result of each function. Windows Sockets 2 added functions and features with other Windows Sockets error codes returned in addition to those listed in the original Winsock specification. Additional functions have been added over time to enhance Winsock for use by developers. For example, new name service functions (getaddrinfo and getnameinfo, for example) were added that support both IPv6 and IPv4 on WindowsВ XP and later. Some of the older IPv4-only name service functions (the getXbyY class of functions, for example) have been deprecated.
A complete list of possible error codes returned by Windows Sockets functions is given in the section on Windows Sockets Error Codes.
Коды ошибок — errno, h_errno и WSAGetLastError
В приложениях Winsock коды ошибок извлекаются с помощью функции WSAGetLastError, замены сокетов Windows для функции GetLastError Windows. Коды ошибок, возвращаемые Windows Сокетами, похожи на константы кода ошибки сокета UNIX, но все константы имеют префикс WSA. Поэтому в приложениях Winsock возвращается код ошибки WSAEWOULDBLOCK, а в UNIX приложениях возвращается код ошибки EWOULDBLOCK.
Коды ошибок, заданные Windows Сокеты, недоступны через переменную errno. Кроме того, для класса функций getXbyY коды ошибок недоступны через переменную h_errno . Функция WSAGetLastError предназначена для обеспечения надежного способа для потока в многопоточных процессах для получения сведений об ошибках для каждого потока.
Для совместимости с Berkeley UNIX (BSD) ранние версии Windows (Windows 95 с обновлением Windows Socket 2 и Windows 98, например) переопределили обычные константы ошибок Berkeley, обычно найденные в errno.h в BSD в качестве эквивалентных ошибок Windows Sockets WSA. Например, ECONNREFUSED был определен как WSAECONNREFUSED в файле заголовка Winsock.h . В последующих версиях Windows (Windows NT 3.1 и более поздних версий) эти определения были закомментированы, чтобы избежать конфликтов с errno.h, используемых с Microsoft C/C++ и Visual Studio.
Файл заголовка Winsock2.h, включенный в пакет средств разработки программного обеспечения Windows (SDK), пакет СРЕДСТВ разработки программного обеспечения платформы (SDK) и Visual Studio по-прежнему содержит блок закомментированных определений в #ifdef 0 и блок #endif, определяющий коды ошибок сокета BSD, которые должны совпадать с константами ошибок WSA. Их можно использовать для обеспечения совместимости с программированием сокетов UNIX, BSD и Linux. Для совместимости с BSD приложение может изменить Winsock2.h и раскомментировать этот блок. Однако разработчикам приложений настоятельно не рекомендуется раскомментывать этот блок из-за неизбежных конфликтов с errno.h в большинстве приложений. Кроме того, ошибки сокета BSD определяются очень разными значениями, чем используются в программах UNIX, BSD и Linux. Разработчикам приложений настоятельно рекомендуется использовать константы ошибок WSA в приложениях сокетов.
Эти определения остаются закомментированы в заголовке Winsock2.h в блоке #ifdef 0 и #endif. Если разработчик приложения настаивает на использовании кодов ошибок BSD для совместимости, приложение может включить строку формы:
Это позволяет сетевому коду, написанному для использования глобального объекта errno , правильно работать в однопоточной среде. Есть некоторые очень серьезные недостатки. Если исходный файл содержит код, который проверяет errno для функций сокета и не сокета, этот механизм нельзя использовать. Кроме того, приложению невозможно назначить новое значение errno. (В Windows Сокетах функция WSASetLastError может использоваться для этой цели.)
Типичный стиль BSD
Хотя константы ошибок, согласованные с Berkeley Sockets 4.3, предоставляются для обеспечения совместимости, приложения настоятельно рекомендуется использовать определения кода ошибок WSA. Это связано с тем, что коды ошибок, возвращаемые определенными функциями сокетов Windows, попадают в стандартный диапазон кодов ошибок, определенных Microsoft C©. Таким образом, лучшей версией предыдущего фрагмента исходного кода является:
Исходная спецификация Winsock 1.1, определенная в 1995 году, рекомендовала набор кодов ошибок и перечислила возможные ошибки, которые могут быть возвращены в результате каждой функции. Windows Сокеты 2 добавлены функции и функции с другими кодами ошибок сокетов Windows, возвращенными в дополнение к указанным в исходной спецификации Winsock. Дополнительные функции были добавлены со временем, чтобы улучшить Winsock для использования разработчиками. Например, добавлены новые функции службы имен (getaddrinfo и getnameinfo, например), поддерживающие IPv6 и IPv4 в Windows XP и более поздних версий. Некоторые из старых функций службы имен только IPv4 (например, класс функций getXbyY ) устарели.
Полный список возможных кодов ошибок, возвращаемых функциями Windows Sockets, приведен в разделе Windows Коды ошибок сокетов.
WSAGetOverlappedResult function (winsock2.h)
The WSAGetOverlappedResult function retrieves the results of an overlapped operation on the specified socket.
Syntax
Parameters
A descriptor identifying the socket.
This is the same socket that was specified when the overlapped operation was started by a call to any of the Winsock functions that supports overlapped operations. These functions include AcceptEx, ConnectEx, DisconnectEx, TransmitFile, TransmitPackets, WSARecv, WSARecvFrom, LPFN_WSARECVMSG (WSARecvMsg), WSASend, WSASendMsg, WSASendTo, and WSAIoctl.
A pointer to a WSAOVERLAPPED structure that was specified when the overlapped operation was started. This parameter must not be a NULL pointer.
A pointer to a 32-bit variable that receives the number of bytes that were actually transferred by a send or receive operation, or by the WSAIoctl function. This parameter must not be a NULL pointer.
A flag that specifies whether the function should wait for the pending overlapped operation to complete. If TRUE, the function does not return until the operation has been completed. If FALSE and the operation is still pending, the function returns FALSE and the WSAGetLastError function returns WSA_IO_INCOMPLETE. The fWait parameter may be set to TRUE only if the overlapped operation selected the event-based completion notification.
A pointer to a 32-bit variable that will receive one or more flags that supplement the completion status. If the overlapped operation was initiated through WSARecv or WSARecvFrom, this parameter will contain the results value for lpFlags parameter. This parameter must not be a NULL pointer.
Return value
If WSAGetOverlappedResult succeeds, the return value is TRUE. This means that the overlapped operation has completed successfully and that the value pointed to by lpcbTransfer has been updated.
If WSAGetOverlappedResult returns FALSE, this means that either the overlapped operation has not completed, the overlapped operation completed but with errors, or the overlapped operation’s completion status could not be determined due to errors in one or more parameters to WSAGetOverlappedResult. On failure, the value pointed to by lpcbTransfer will not be updated. Use WSAGetLastError to determine the cause of the failure (either by the WSAGetOverlappedResult function or by the associated overlapped operation).
Error code | Meaning |
---|---|
WSANOTINITIALISED | A successful WSAStartup call must occur before using this function. |
WSAENETDOWN | The network subsystem has failed. |
WSAENOTSOCK | The descriptor is not a socket. |
WSA_INVALID_HANDLE | The hEvent parameter of the WSAOVERLAPPED structure does not contain a valid event object handle. |
WSA_INVALID_PARAMETER | One of the parameters is unacceptable. |
WSA_IO_INCOMPLETE | The fWait parameter is FALSE and the I/O operation has not yet completed. |
WSAEFAULT | One or more of the lpOverlapped, lpcbTransfer, or lpdwFlags parameters are not in a valid part of the user address space. This error is returned if the lpOverlapped, lpcbTransfer, or lpdwFlags parameter was a NULL pointer on Windows ServerВ 2003 and earlier. |
Remarks
The WSAGetOverlappedResult function reports the results of the overlapped operation specified in the lpOverlapped parameter for the socket specified in the s parameter. The WSAGetOverlappedResult function is passed the socket descriptor and the WSAOVERLAPPED structure that was specified when the overlapped function was called. A pending operation is indicated when the function that started the operation returns FALSE and the WSAGetLastError function returns WSA_IO_PENDING. When an I/O operation such as WSARecv is pending, the function that started the operation resets the hEvent member of the WSAOVERLAPPED structure to the nonsignaled state. Then, when the pending operation has completed, the system sets the event object to the signaled state.
If the fWait parameter is TRUE, WSAGetOverlappedResult determines whether the pending operation has been completed by waiting for the event object to be in the signaled state. A client may set the fWait parameter to TRUE, but only if it selected event-based completion notification when the I/O operation was requested. If another form of notification was selected, the usage of the hEvent parameter of the WSAOVERLAPPED structure is different, and setting fWait to TRUE causes unpredictable results.
If the WSAGetOverlappedResult function is called with the lpOverlapped, lpcbTransfer, or lpdwFlags parameter set to a NULL pointer on WindowsВ Vista, this will result in an access violation. If the WSAGetOverlappedResult function is called with the lpOverlapped, lpcbTransfer, or lpdwFlags parameter set to a NULL pointer on Windows ServerВ 2003 and earlier, this will result in the WSAEFAULT error code being returned.
WindowsВ 8.1 and Windows ServerВ 2012В R2: This function is supported for Windows Store apps on WindowsВ 8.1, Windows ServerВ 2012В R2, and later.