Windows Sockets 2 Application Programming Interface
Windows Sockets 2 Application Programming Interface
Application Programming
Interface
An Interface for Transparent Network Programming
Under Microsoft WindowsTM
Revision 2.2.2
August 7, 1997
ii
Table of Contents
1. INTRODUCTION ....................................................................................................................................1
1.1. Intended Audience ...................................................................................................................................2
1.2. Document Organization...........................................................................................................................2
1.3. Status of This Specification .....................................................................................................................2
1.4. Document Version Conventions ..............................................................................................................3
1.5. New And/Or Different in Version 2.2.1...................................................................................................3
1.6. New And/Or Different in Version 2.2.2...................................................................................................3
2. SUMMARY OF NEW CONCEPTS, ADDITIONS AND CHANGES FOR WINSOCK 2................4
2.1. WinSock 2 Architecture...........................................................................................................................4
2.1.1. Simultaneous Access to Multiple Transport Protocols .....................................................................4
2.1.2. Backwards Compatibility For WinSock 1.1 Applications ................................................................4
2.1.2.1. Source Code Compatibility.........................................................................................................................4
2.1.2.2. Binary Compatibility...................................................................................................................................5
2.2. Making Transport Protocols Available To WinSock...............................................................................5
2.2.1. Layered Protocols and Protocol Chains............................................................................................6
2.2.2. Using Multiple Protocols ..................................................................................................................6
2.2.3. Multiple Provider Restrictions on select() ........................................................................................7
2.3. Function Extension Mechanism...............................................................................................................7
2.4. Debug and Trace Facilities ......................................................................................................................8
2.5. Protocol Independent Name Resolution ..................................................................................................8
2.6. Overlapped I/O and Event Objects ..........................................................................................................8
2.6.1. Event Objects....................................................................................................................................9
2.6.2. Receiving Completion Indications..................................................................................................10
2.6.2.1. Blocking and Waiting for Completion Indication.....................................................................................10
2.6.2.2. Polling for Completion Indication ............................................................................................................10
2.6.2.3. Using socket I/O completion routines.......................................................................................................10
2.6.2.4. Summary of overlapped completion indication mechanisms ....................................................................10
2.6.3. WSAOVERLAPPED Details .........................................................................................................11
2.7. Asynchronous Notification Using Event Objects ..................................................................................11
2.8. Quality of Service ..................................................................................................................................12
2.8.1. The QOS Structure .........................................................................................................................13
2.8.2. QOS Templates...............................................................................................................................16
2.8.3. Default Values ................................................................................................................................16
2.9. Socket Groups........................................................................................................................................16
2.10. Shared Sockets.....................................................................................................................................17
2.11. Enhanced Functionality During Connection Setup and Teardown ......................................................17
2.12. Extended Byte Order Conversion Routines .........................................................................................18
2.13. Support for Scatter/Gather I/O.............................................................................................................18
2.14. Protocol-Independent Multicast and Multipoint ..................................................................................19
2.15. Summary of New Socket Options........................................................................................................19
2.16. Summary of New Socket Ioctl Opcodes ..............................................................................................20
2.17. Summary of New Functions.................................................................................................................22
2.17.1. Generic Data Transport Functions ................................................................................................22
2.17.2. Name Registration and Resolution Functions ...............................................................................22
3. WINDOWS SOCKETS PROGRAMMING CONSIDERATIONS....................................................24
3.1. Deviation from BSD Sockets.................................................................................................................24
3.1.1. Socket Data Type............................................................................................................................24
3.1.2. select() and FD_*............................................................................................................................24
3.1.3. Error codes - errno, h_errno & WSAGetLastError() ......................................................................24
3.1.4. Pointers ...........................................................................................................................................25
iii
3.1.5. Renamed functions..........................................................................................................................25
3.1.5.1. close() and closesocket()...........................................................................................................................25
3.1.5.2. ioctl() and ioctlsocket()/WSAIoctl() .........................................................................................................25
3.1.6. Maximum number of sockets supported .........................................................................................26
3.1.7. Include files ....................................................................................................................................26
3.1.8. Return values on function failure....................................................................................................26
3.1.9. Raw Sockets....................................................................................................................................26
3.2. Byte Ordering ........................................................................................................................................26
3.3. WinSock 1.1 Compatibility Issues.........................................................................................................27
3.3.1. Default state for a socket’s overlapped attribute.............................................................................27
3.3.2. Winsock 1.1 Blocking routines & EINPROGRESS .......................................................................27
3.4. Graceful shutdown, linger options and socket closure...........................................................................29
3.5. Out-Of-Band data ..................................................................................................................................30
3.5.1. Protocol Independent OOB data.....................................................................................................30
3.5.2. OOB data in TCP............................................................................................................................31
3.6. Summary of WinSock 2 Functions ........................................................................................................32
3.6.1. BSD Socket Functions ....................................................................................................................32
3.6.2. Microsoft Windows-specific Extension Functions .........................................................................33
4. SOCKET LIBRARY REFERENCE.....................................................................................................36
4.1. accept() ..................................................................................................................................................36
4.2. bind() .....................................................................................................................................................38
4.3. closesocket() ..........................................................................................................................................40
4.4. connect() ................................................................................................................................................42
4.5. getpeername() ........................................................................................................................................46
4.6. getsockname()........................................................................................................................................47
4.7. getsockopt() ...........................................................................................................................................49
4.8. htonl() ....................................................................................................................................................54
4.9. htons()....................................................................................................................................................55
4.10. ioctlsocket() .........................................................................................................................................56
4.11. listen()..................................................................................................................................................58
4.12. ntohl() ..................................................................................................................................................60
4.13. ntohs()..................................................................................................................................................61
4.14. recv() ...................................................................................................................................................62
4.15. recvfrom()............................................................................................................................................65
4.16. select() .................................................................................................................................................68
4.17. send() ...................................................................................................................................................71
4.18. sendto() ................................................................................................................................................74
4.19. setsockopt()..........................................................................................................................................78
4.20. shutdown() ...........................................................................................................................................83
4.21. socket() ................................................................................................................................................85
4.22. WSAAccept() ......................................................................................................................................88
4.23. WSAAsyncSelect()..............................................................................................................................92
4.24. WSACancelBlockingCall()................................................................................................................100
4.25. WSACleanup() ..................................................................................................................................102
4.26. WSACloseEvent() .............................................................................................................................103
4.27. WSAConnect() ..................................................................................................................................104
4.28. WSACreateEvent() ............................................................................................................................109
4.29. WSADuplicateSocket() .....................................................................................................................110
4.30. WSAEnumNetworkEvents()..............................................................................................................113
4.31. WSAEnumProtocols() .......................................................................................................................116
4.32. WSAEventSelect().............................................................................................................................121
4.33. WSAGetLastError()...........................................................................................................................127
4.34. WSAGetOverlappedResult() .............................................................................................................128
4.35. WSAGetQOSByName() ....................................................................................................................130
iv
4.36. WSAHtonl().......................................................................................................................................131
4.37. WSAHtons() ......................................................................................................................................132
4.38. WSAIoctl() ........................................................................................................................................133
4.39. WSAIsBlocking() ..............................................................................................................................143
4.40. WSAJoinLeaf()..................................................................................................................................144
4.41. WSANtohl().......................................................................................................................................149
4.42. WSANtohs() ......................................................................................................................................150
4.43. WSARecv() .......................................................................................................................................151
4.44. WSARecvDisconnect()......................................................................................................................157
4.45. WSARecvFrom()...............................................................................................................................159
4.46. WSAResetEvent()..............................................................................................................................165
4.47. WSASend()........................................................................................................................................166
4.48. WSASendDisconnect()......................................................................................................................171
4.49. WSASendTo() ...................................................................................................................................173
4.50. WSASetBlockingHook() ...................................................................................................................179
4.51. WSASetEvent() .................................................................................................................................181
4.52. WSASetLastError() ...........................................................................................................................182
4.53. WSASocket().....................................................................................................................................183
4.54. WSAStartup() ....................................................................................................................................187
4.55. WSAUnhookBlockingHook()............................................................................................................191
4.56. WSAWaitForMultipleEvents() ..........................................................................................................192
4.57. WSAProviderConfigChange()...........................................................................................................194
5. NAME RESOLUTION AND REGISTRATION ...............................................................................196
5.1. Protocol-Independent Name Resolution ..............................................................................................196
5.1.1. Name Resolution Model ...............................................................................................................196
5.1.1.1. Types of Name Spaces ............................................................................................................................196
5.1.1.2. Name Space Organization.......................................................................................................................197
5.1.1.3. Name Space Provider Architecture .........................................................................................................197
5.1.2. Summary of Name Resolution Functions......................................................................................198
5.1.2.1. Service Installation..................................................................................................................................198
5.1.2.2. Client Query............................................................................................................................................199
5.1.2.3. Helper Functions.....................................................................................................................................199
5.1.3. Name Resolution Data Structures .................................................................................................200
5.1.3.1. Query-Related Data Structures................................................................................................................200
5.1.3.2. Service Class Data Structures .................................................................................................................201
5.2. Name Resolution Function Reference .................................................................................................203
5.2.1. WSAAddressToString()...............................................................................................................203
5.2.2. WSAEnumNameSpaceProviders() ..............................................................................................205
5.2.3. WSAGetServiceClassInfo.............................................................................................................207
5.2.4. WSAGetServiceClassNameByClassId()......................................................................................208
5.2.5. WSAInstallServiceClass() ...........................................................................................................209
5.2.6. WSALookupServiceBegin() ........................................................................................................210
5.2.7. WSALookupServiceEnd() ...........................................................................................................213
5.2.8. WSALookupServiceNext()..........................................................................................................214
5.2.9. WSARemoveServiceClass() ........................................................................................................217
4.2.10. WSASetService()........................................................................................................................218
5.2.10. WSAStringToAddress().............................................................................................................221
5.3. WinSock 1.1 Compatibile Name Resolution for TCP/IP.....................................................................222
5.3.1. Introduction ..................................................................................................................................222
5.3.2. Basic Approach.............................................................................................................................222
5.3.3. getprotobyname and getprotobynumber........................................................................................222
5.3.4. getservbyname() and getservbyport() ...........................................................................................223
5.3.5. gethostbyname()............................................................................................................................223
5.3.6. gethostbyaddr() .............................................................................................................................223
v
5.3.7. gethostname() ...............................................................................................................................223
5.4. WinSock 1.1 Compatible Name Resolution Reference .......................................................................224
5.4.1. gethostbyaddr() .............................................................................................................................224
5.4.2. gethostbyname()............................................................................................................................226
5.4.3. gethostname() ...............................................................................................................................228
5.4.4. getprotobyname()..........................................................................................................................229
5.4.5. getprotobynumber() ......................................................................................................................231
5.4.6. getservbyname()............................................................................................................................232
5.4.7. getservbyport()..............................................................................................................................234
5.4.8. inet_addr() ....................................................................................................................................236
5.4.9. inet_ntoa().....................................................................................................................................237
5.4.10. WSAAsyncGetHostByAddr().....................................................................................................238
5.4.11. WSAAsyncGetHostByName() ...................................................................................................241
5.4.12. WSAAsyncGetProtoByName() ..................................................................................................244
5.4.13. WSAAsyncGetProtoByNumber()...............................................................................................247
5.4.14. WSAAsyncGetServByName()....................................................................................................250
5.4.15. WSAAsyncGetServByPort() ......................................................................................................253
5.4.16. WSACancelAsyncRequest() .......................................................................................................256
APPENDIX A. ERROR CODES AND HEADER FILES AND DATA TYPES .................................258
A.1 Error Codes...........................................................................................................................................258
A.1.1 Error Codes - Brief Description.....................................................................................................258
A.1.2 Error Codes - Extended Description ..............................................................................................260
A.2 Header Files ..........................................................................................................................................266
A.2.1 Berkeley Header Files....................................................................................................................266
A.2.2 WinSock Header File - Winsock2.h...............................................................................................267
A.2.3 Sizes of Data Types .......................................................................................................................268
APPENDIX B. MULTIPOINT AND MULTICAST SEMANTICS......................................................269
B.1. Multipoint and Multicast Introduction .................................................................................................269
B.2 Multipoint Taxonomy ...........................................................................................................................269
B.3 WinSock 2 Interface Elements for Multipoint and Multicast................................................................270
B.3.1. Attributes in WSAPROTOCOL_INFO struct...............................................................................270
B.3.2. Flag bits for WSASocket()............................................................................................................270
B.3.3. SIO_MULTIPOINT_LOOP command code for WSAIoctl() .......................................................271
B.3.4. SIO_MULTICAST_SCOPE command code for WSAIoctl().......................................................271
B.3.5. WSAJoinLeaf() .............................................................................................................................271
B.4. Semantics for joining multipoint leaves ...............................................................................................271
B.4.1. Using WSAJoinLeaf()...................................................................................................................272
B.5. Semantic differences between multipoint sockets and regular sockets.................................................273
B.6. How existing multipoint protocols support these extensions ...............................................................273
B.6.1. IP multicast ...................................................................................................................................273
B.6.2. ATM Point to Multipoint ..............................................................................................................274
APPENDIX C. THE LAME LIST ..........................................................................................................275
vi
Acknowledgments
Windows Sockets Version 2
Since The WinSock Group started the Version 2 specification process in May 1994, hundreds of people,
companies and organizations have cooperated and contributed to its design and specification. Several
meetings, many emails and telephone conversations later, it’s appropriate to acknowledge the part played by
everyone and certain contributors in particular.
Many individuals too numerous to mention have given time to the project and all of them are owed a debt of
thanks for the roles they played in creating the most comprehensive open transport API designed to date.
The commitment, dedication and energy of the following individuals and companies should be singled out
for special attention.
First, the design of WinSock 2 was based on the input of multiple “Functionality Groups” whose leaders
cajoled, steered, defined and refined each of their group’s technical proposals. Consequently, we’d like to
recognize the following individuals and their employers for the time and effort they have given. It’s
appropriate to thank Dave Andersen for the challenge he undertook, met and surpassed in defining the
generic API set and pulling together the contributions of all the various Functionality Groups.
The following individuals moderated the WinSock 2 effort as a whole and provided the framework,
technical guidance and administrative mechanisms for WinSock Version 2.
Special thanks to Microsoft and Intel for the amount of time these companies gave to the specification and
especially to Dave Treadwell and Keith Moore at Microsoft and Dave Andersen and Charlie Tai at Intel for
their considerable editorial efforts on the WinSock 2 specifications.
The SDK for Windows NT and Windows 95 was a project in its own right and was brought about by a joint
effort between Microsoft and the Intel Architecture Labs. The Microsoft team included Dave Treadwell,
vii
Steve Firebaugh, Keith Moore, Arnold Miller, Francis X. Langlois, Mosin Ahmed, Chris Steck and Dave
Beaver. The Intel team included Dave Andersen, Dave Doerner, Paul Drews, Charlie Tai, Dirk Brandewie,
Dan Chou, Michael Grafton and Dan Ohlemacher.
This version would not, of course, have been possible without the effort of the contributors to WinSock
Version 1.1 and the numerous products that implement and use it. Of special significance to the success of
WinSock are the hundreds of shareware and freeware applications that have been developed and continue to
emerge. The authors of these packages are some of WinSock’s unsung heroes. It’s fitting to recognize, at
least, the role of and contribution made by Peter Tattam’s “Trumpet” WinSock implementation.
We’d like to thank Interop for hosting the kick-off meeting for WinSock Version 2, and Novell for kindly
providing the facilities for the meeting that marked the consolidation effort which brought together the work
of different groups into a coordinated API and SPI definition.
Sincerely,
Martin Hall
Stardust Technologies
viii
Introduction 1
1. Introduction
This document specifies the Windows Sockets 2 programming interface. Windows Sockets 2 utilizes the
sockets paradigm as first popularized in BSD UNIX1 and as adapted for Microsoft Windows in the
Windows Sockets 1.1 specification. While historically sockets programming in general and Windows
Sockets programming in particular has been TCP/IP-centric, this is no longer the case. Consequently, it is
important to realize that Windows Sockets 2 is an interface and not a protocol. As an interface it is used to
discover and utilize the communications capabilities of any number of underlying transport protocols.
Because it is not a protocol, it does not in any way affect the “bits on the wire”, and does not need to be
utilized on both ends of a communications link.
The motivation in creating version 2 of Windows Sockets was primarily to provide a protocol-independent
transport interface that is fully capable of supporting emerging networking capabilities including real-time
multimedia communications. Thus Windows Sockets 2 is a true superset of the widely deployed Windows
Sockets 1.1 interface. While maintaining full backwards compatibility it extends the Windows Sockets
interface in a number of areas including
• Access to protocols other than TCP/IP: WinSock 2 allows an application to use the familiar socket
interface to achieve simultaneous access to any number of installed transport protocols.
• Protocol-independent name resolution facilities: WinSock 2 includes a standardized set of APIs for
querying and working with the myriad of name resolution domains that exist today (e.g. DNS, SAP,
X.500, etc.)
• Overlapped I/O with scatter/gather: following the model established in Win32 environments, WinSock
2 incorporates the overlapped paradigm for socket I/O and incorporates scatter/gather capabilities as
well.
• Quality of service: WinSock 2 establishes conventions for applications to negotiate required service
levels for parameters such as bandwidth and latency. Other QOS-related enhancements include socket
grouping and prioritization, and mechanisms for network-specific QOS extensions.
• Protocol-independent multicast and multipoint: applications can discover what type of multipoint or
multicast capabilities a transport provides and use these facilities in a generic manner.
• Other frequently requested extensions: shared sockets, conditional acceptance, exchange of user data at
connection setup/teardown time, protocol-specific extension mechanisms.
It is almost always the case that adding more capability and functionality also increases the level of
complexity, and Windows Sockets 2 is no exception. We have attempted to mitigate this as much as
possible by extending the familiar sockets interface as opposed to starting from scratch. While this
approach offers significant benefit to experienced socket programmers, it may occasionally vex them as
well since certain widely held assumptions are no longer valid. For example, many sockets programmers
assume that all connectionless protocols use SOCK_DGRAM sockets and all connection-oriented protocols
use SOCK_STREAM sockets. In WinSock 2 SOCK_DGRAM and SOCK_STREAM are only two of
many possible socket types, and programmers should no longer rely on socket type to describe all of the
essential attributes of a transport protocol.
With its vastly larger scope, Windows Sockets 2 takes the socket paradigm considerably beyond what it’s
original designers contemplated. As a consequence, a number of new functions have been added, all of
which are assigned names that are prefixed with “WSA”. In all but a few instances these new functions are
expanded versions of an existing function from BSD sockets. The need to retain backwards compatibility
mandates that we retain both the “just plain” BSD functions and the new “WSA” versions, which in turn
amplifies the perception of WinSock 2 as being large and complex. This stretching of the sockets paradigm
also requires us to occasionally dance around areas where the original sockets architecture is on shaky
1
UNIX is a trademark of UNIX Systems Laboratories, Inc.
2 Introduction
ground. A telling example of this is the unfortunate, but now irrevocable, decision to combine the notions
of address family and protocol family.
Persons who are interested in developing applications that will take advantage of WinSock 2’s capabilities
will be primarily interested in this API specification. Persons who are interested in making a particular
transport protocol available under the WinSock 2 interface will need to be familiar with the WinSock 2
Service Provider Interface (SPI) Specification as well. The Windows Sockets 2 SPI specification exists
under separate cover.
This document (Windows Sockets 2 Application Programming Interface) is divided into four main
sections and four appendices.
The Windows Sockets 2 Protocol-Specific Annex contains information specific to a number of transport
protocols that are accessible via Windows Sockets 2. The Windows Sockets 2 Service Provider Interface
specifies the interface that transport providers must conform to in order to be accessible via Windows
Sockets 2. Windows Sockets 2 Debug-Trace DLL describes the files and mechanics of the debug-trace
DLL. This is a useful tool for application developers and service providers alike, that shows API and SPI
calls in and out of the WinSock 2 DLL..
This document comprises only the API portion of the Windows Sockets 2 specification. The WinSock
Group’s Generic API Extensions functionality group produced the initial versions of this document as well
Introduction 3
as the Windows Sockets 2 Protocol-Specific Annex. Constructive comments and feedback on this material
are always welcome and should be directed towards:
David B. Andersen
Intel Architecture Labs
andersen@ibeam.jf.intel.com
WinSock 2 WinSock 2
Application Application
WinSock 2 API
WinSock 2 WinSock 2
Transport SPI Name Space SPI
Note: for simplicity’s sake the WS2_32.DLL will be referred to simply as WinSock 2 DLL.
With the above architecture, it is no longer necessary (or desirable) for each stack vendor to supply their
own implementation of WinSock 2 DLL, since a single WinSock 2 DLL must work across all stacks. The
WinSock 2 DLL and compatibility shims should thus be viewed in the same light as an operating system
component.
Winsock 1.1 Blocking routines & EINPROGRESS for more information. This means that existing WinSock
1.1 application source code can easily be moved to the WinSock 2 system at a simple level by including the
new header file “winsock2.h” and performing a straightforward re-link with the appropriate WinSock 2
libraries. Application developers are encouraged to view this as merely the first step in a full transition to
WinSock Version 2. This is because there are numerous ways in which a WinSock 1.1 application can be
improved by exploring and using functionality that is new in WinSock Version 2.
WinSock 2 API
API
WinSock 2 SPI’s
TCP/IP TCP/IP-based
Transport Namespace
Service Provider Service Provider
e.g. DNS
WinSock 1.1 applications currently use certain elements from the WSAData structure (obtained via a call
to WSAStartup()) to obtain information about the underlying TCP/IP stack.. These include: iMaxSockets,
iMaxUdpDg, and lpVendorInfo. While WinSock 2 applications will know to ignore these values (since
they cannot uniformly apply to all available protocol stacks), safe values are supplied to avoid breaking
WinSock 1.1 applications.
Note that transport stacks that are thus installed are considered to be WinSock service providers, and
hereafter are referred to as such. The WinSock 2 SDK includes a small Windows applet called
SPORDER.EXE that will allow the user to view and modify the order in which service providers are
enumerated. Using this applet, a user may manually establish a particular TCP/IP protocol stack as the
default TCP/IP provider if more than one such stack is present.
The functions that this applet uses to reorder the service providers are exported from a DLL
(SPORDER.DLL). As a result, installation applications may use the interface of SPORDER.DLL to
6 New Concepts, Additions and Changes
programmatically reorder service providers, to suit their needs. Please refer to the Service Provider
Interface document for a detailed description of the interface.
This stringing together of one or more layered protocols and a base protocol into chains can be
accomplished by arranging for the layered protocols to support the WinSock 2 SPI at both their upper and
lower edges. A special WSAPROTOCOL_INFO struct is created which refers to the protocol chain as a
whole, and which describes the explicit order in which the layered protocols are joined. This is illustrated
in Figure 3. Note that since only base protocols and protocol chains are directly usable by applications,
only these protocols are listed when the installed protocols are enumerated with WSAEnumProtocols().
message-oriented (i.e. the sender’s message boundaries are preserved by the network), but the receiving end
may choose to ignore these message boundaries and treat the socket as a byte stream. Thus there could
reasonably be two different WSAPROTOCOL_INFO struct entries for SPX, one for each of these
behaviors.
Whereas in WinSock 1.1 there is a single address family (AF_INET) comprising a small number of well-
known socket types and protocol identifiers, the focus will shift for WinSock 2. The existing address
family, socket type and protocol identifiers are retained for compatibility reasons, but many new address
family, socket type and protocol values will appear which are unique but not necessarily well known. Not
being well known need not pose a problem since applications that desire to be protocol-independent are
encouraged to select protocols for use on the basis of their suitability rather than the particular values
assigned to their socket_type or protocol fields. Protocol suitability is indicated by the communications
attributes (e.g. message vs. byte-stream oriented, reliable vs. unreliable, etc.) contained within the
protocol’s WSAPROTOCOL_INFO struct. Selecting protocols on the basis of suitability as opposed to
well-known protocol names and socket types allows protocol-independent applications to take advantage of
new transport protocols and their associated media types as they become available.
In terms of the well-known client/server paradigm, the server half of a client/server application will benefit
by establishing listening sockets on all suitable transport protocols. The client, then, may establish its
connection using any suitable protocol. This would enable, for example, a client application to be
unmodified whether it was running on a desktop system connected via LAN or on a laptop using a wireless
network.
A WinSock 2 clearinghouse has been established for protocol stack vendors to obtain unique identifiers for
new address families, socket types and protocols. FTP and world-wide web servers are used to supply
current identifier/value mappings, and email is used to request allocation of new ones. At the time of this
writing the world-wide web URL for the Windows Sockets 2 Identifier Clearinghouse is
http://www.stardust.com/wsresource/winsock2/ws2ident.html
In order to invoke an extension function, the application must first ask for a pointer to the desired function.
This is done via the WSAIoctl() function using the SIO_GET_EXTENSION_FUNCTION_POINTER
command code. The input buffer to the WSAIoctl() function contains an identifier for the desired
8 New Concepts, Additions and Changes
extension function and the output buffer will contain the function pointer itself. The application can then
invoke the extension function directly without passing through the WinSock 2 DLL.
The identifiers assigned to extension functions are globally unique identifiers (GUIDs) that are allocated by
service provider vendors.. Vendors who create extension functions are urged to publish full details about
the function including the syntax of the function prototype. This makes it possible for common and/or
popular extension functions to be offered by more than one service provider vendor. An application can
obtain the function pointer and use the function without needing to know anything about the particular
service provider that implements the function.
Developers can use this mechanism to trace procedure calls, procedure returns, parameter values, and return
values. Parameter values and return values can be altered on procedure-call or procedure-return. If desired,
a procedure-call can even be prevented or redirected. With access to this level of information and control,
it should be easy for a developer to isolate any problem to the application, WinSock 2 DLL or service
provider.
The WinSock 2 SDK includes the instrumented WinSock 2 DLL, a sample debug/trace DLL and a
document containing a detailed description of the above two components. The sample debug/trace DLL is
provided in both source and object form. Developers are free to use the source to develop versions of the
debug/trace DLL that meet their special needs.
Note that creating a socket with the overlapped attribute has no impact on whether a socket is currently in
the blocking or non-blocking mode. Sockets created with the overlapped attribute may be used to perform
overlapped I/O, and doing so does not change the blocking mode of a socket. Since overlapped I/O
operations do not block, the blocking mode of a socket is irrelevant for these operations.
For receiving, applications use WSARecv() or WSARecvFrom() to supply buffers into which data is to be
received. If one or more buffers are posted prior to the time when data has been received by the network, it
is possible that data will be placed into the user’s buffers immediately as it arrives and thereby avoid the
copy operation that would otherwise occur at the time the recv() or recvfrom() function is invoked. If data
is already present when receive buffers are posted, it is copied immediately into the user’s buffers. If data
arrives when no receive buffers have been posted by the application, the network resorts to the familiar
synchronous style of operation where the incoming data is buffered internally until such time as the
New Concepts, Additions and Changes 9
application issues a receive call and thereby supplies a buffer into which the data may be copied. An
exception to this would be if the application used setsockopt() to set the size of the receive buffer to zero.
In this instance, reliable protocols would only allow data to be received when application buffers had been
posted, and data on unreliable protocols would be lost.
On the sending side, applications use WSASend() or WSASendTo() to supply pointers to filled buffers and
then agree to not disturb the buffers in any way until such time as the network has consumed the buffer's
contents.
Overlapped send and receive calls return immediately. A return value of zero indicates that the I/O
operation completed immediately and that the corresponding completion indication has already occurred.
That is, the associated event object has been signaled, or a completion routine has been queued and will be
executed when the calling thread gets into the alterable wait state. A return value of SOCKET_ERROR
coupled with an error code of WSA_IO_PENDING indicates that the overlapped operation has been
successfully initiated and that a subsequent indication will be provided when send buffers have been
consumed or when a receive operation has been completed. However, for byte stream style sockets, the
completion indication occurs whenever the incoming data is exhausted, regardless of whether the buffers
are fully filled. Any other error code indicates that the overlapped operation was not successfully initiated
and that no completion indication will be forthcoming.
Both send and receive operations can be overlapped. The receive functions may be invoked multiple times
to post receive buffers in preparation for incoming data, and the send functions may be invoked multiple
times to queue up multiple buffers to be sent. Note that while the application can rely upon a series of
overlapped send buffers being sent in the order supplied, the corresponding completion indications may
occur in a different order. Likewise, on the receiving side, buffers will be filled in the order they are
supplied but the completion indications may occur in a different order.
There is no way to cancel individual overlapped operations pending on a given socket, however, the
closesocket() function can be called to close the socket and eventually discontinue all pending operations.
The deferred completion feature of overlapped I/O is also available for WSAIoctl() which is an enhanced
version of ioctlsocket().
Applications use WSACreateEvent() to obtain an event object handle which may then be supplied as a
required parameter to the overlapped versions of send and receive calls (WSASend(), WSASendTo(),
WSARecv(), WSARecvFrom()). The event object, which is cleared when first created, is set by the
transport providers when the associated overlapped I/O operation has completed (either successfully or with
errors). Each event object created by WSACreateEvent() should have a matching WSACloseEvent() to
destroy it.
Event objects are also used in WSAEventSelect() to associate one or more FD_XXX network events with
an event object. This is described in section 2.7. Asynchronous Notification Using Event Objects.
Transports allow an application to invoke send and receive operations from within the context of the socket
I/O completion routine, and guarantee that, for a given socket, I/O completion routines will not be nested.
This permits time-sensitive data transmissions to occur entirely within a preemptive context.
message to be sent on the occurrence of an FD_XXX network event (e.g.. FD_READ, FD_WRITE, etc.),
an application-designated event object is set.
Also, the fact that a particular FD_XXX network event has occurred is “remembered” by the service
provider. The application may call WSAEnumNetworkEvents() to have the current contents of the
network event memory copied to an application supplied buffer and to have the network event memory
atomically cleared. If desired, the application may also designate a particular event object which is cleared
along with the network event memory.
Flow specs describe a set of characteristics about a proposed unidirectional flow through the network. An
application may associate a pair of flowspecs with a socket (one for each direction) at the time a connection
request is made using WSAConnect(), or at other times using WSAIoctl() with the
SIO_SET_QOS/SIO_SET_GROUP_QOS command. Flowspecs indicate parametrically what level of
service is required and provide a feedback mechanism for applications to use in adapting to network
conditions.
The usage model for QOS in WinSock 2 is as follows. An application may establish its QOS requirements
at any time via WSAIoctl() or coincident with the connect operation via WSAConnect(). For connection-
oriented transports, it is often most convenient for an application to use WSAConnect(), and any QOS
values supplied at connect time supersede those that may have been supplied earlier via WSAIoctl(). If the
WSAConnect() function completes successfully the application knows that its QOS request has been
honored by the network, and the application is then free to use the socket for data exchange. If the connect
operation fails because of limited resources an appropriate error indication is given. At this point the
application may scale down its service request and try again or simply give up.
After every connection attempt (successful or otherwise) transport providers update the associated flow
spec structures in order to indicate, as well as possible, the existing network conditions. (Note that it is
legal to update with the default values defined below to indicate that information about the current network
conditions is not available.) This update from the service provider about current network conditions is
especially useful for the case where the application’s QOS request consisted entirely of the default (i.e.
unspecified) values, which any service provider should be able to agree to. Applications expect to be able
to use this information about current network conditions to guide their use of the network, including any
subsequent QOS requests. Note however, that information provided by the transport in the updated flow
spec structure is only a hint and may be little more than a rough estimate that only applies to the first hop as
opposed to the complete end-to-end connection. The application must take appropriate precautions in
interpreting this information.
Connectionless sockets may also use WSAConnect() to establish a specified QOS level to a single
designated peer. Otherwise connectionless sockets make use of WSAIoctl() to stipulate the initial QOS
request, and any subsequent QOS renegotiations.
Even after a flow is established, conditions in the network may change or one of the communicating parties
may invoke a QOS renegotiation which results in a reduction (or increase) in the available service level. A
notification mechanism is included which utilizes the usual WinSock notification techniques (FD_QOS and
FD_GROUP_QOS events) to indicate to the application that QOS levels have changed. The basic
guideline for a service provider to generate FD_QOS/FD_GROUP_QOS notifications is when the current
level of service supported is significantly different (especially in the negative direction) from what was last
reported. The application should use WSAIoctl() with SIO_GET_QOS and/or SIO_GET_GROUP_QOS
to retrieve the corresponding flow specs and examine them in order to discover what aspect of the service
New Concepts, Additions and Changes 13
level has changed. Note that the QOS structures will be updated as appropriate regardless of whether
FD_QOS/FD_GROUP_QOS is registered and generated. If the updated level of service is not acceptable,
the application may adjust itself to accommodate it, attempt to renegotiate QOS, or close the socket. If a
renegotiation is attempted, a successful return from the WSAIoctl() function indicates that the revised QOS
request was accepted, otherwise an appropriate error will be indicated.
The flow specs proposed for WinSock 2 divide QOS characteristics into the following general areas:
1. Source Traffic Description - The manner in which the application's traffic will be injected into the
network. This includes specifications for the token rate, the token bucket size, and the peak bandwidth.
Note that even though the bandwidth requirement is expressed in terms of a token rate, this does not
mean that service provider must actually implement token buckets. Any traffic management scheme
that yields equivalent behavior is permitted.
2. Latency - Upper limits on the amount of delay and delay variation that are acceptable.
3. Level of service guarantee - Whether or not an absolute guarantee is required as opposed to best effort.
Note that providers which have no feasible way to provide the level of service requested are expected
to fail the connection attempt.
4. Provider-specific parameters - The flowspec itself can be extended in ways that are particular to
specific providers.
typedef struct_WSABUF {
u_long len; /* the length of the buffer */
char FAR * buf; /* the pointer to the buffer */
} WSABUF, FAR * LPWSABUF;
Definitions:
TokenRate/TokenBucketSize A Token bucket model is used to specify the rate at which permission
to send traffic (or credits) accrues. The value of -1 in these variables
indicates that no rate limiting is in force. The TokenRate is expressed
in bytes per second, and the TokenBucketSize in bytes.
PeakBandwidth This field, expressed in bytes/second, limits how fast packets may be
sent back to back from the application. Some intermediate systems
can take advantage of this information resulting in a more efficient
resource allocation.
ServiceType This is the level of service being negotiated for. Values permitted for
level of service are given below.
SERVICETYPE_NOTRAFFIC
In either Sending or Receiving flowspec, indicates that there
will be no traffic in this direction. On duplex capable media,
this signals underlying software to setup unidirectional
connections only.
SERVICETYPE_BESTEFFORT
Indicates that the service provider, at minimum, takes the flow
spec as a guideline and makes reasonable efforts to maintain
New Concepts, Additions and Changes 15
SERVICETYPE_CONTROLLEDLOAD
Indicates that end-to-end behavior provided to an application
by a series of network elements tightly approximates the
behavior visible to applications receiving best-effort service
"under unloaded conditions" from the same series of network
elements. Thus, applications using this service may assume
that: (1) A very high percentage of transmitted packets will be
successfully delivered by the network to the receiving end-
nodes. (Packet loss rate will closely approximate the basic
packet error rate of the transmission medium).; and (2) Transit
delay experienced by a very high percentage of the delivered
packets will not greatly exceed the minimum transit delay
experienced by any successfully delivered packet at the speed
of light.
SERVICETYPE_GUARANTEED
Indicates that the service provider implements a queuing
algorithm which isolates the flow from the effects of other
flows as much as possible, and guarantees the flow the ability
to propagate data at the TokenRate for the duration of the
connection. If the sender sends faster than that rate, the
network may delay or discard the excess traffic. If the sender
does not exceed TokenRate over time, then latency is also
guaranteed. This service type is designed for applications
which require a precisely known quality of service but would
not benefit from better service, such as real-time control
systems.
SERVICETYPE_NETWORK_UNAVAILABLE
In either a Sending or Receiving flowspec, this may be used by
a service provider to indicate a loss of service in the
corresponding direction.
SERVICETYPE_GENERAL_INFORMATION
Indicates that all service types are supported for this traffic
flow.
SERVICETYPE_NOCHANGE
In either a Sending or Receiving flowspec, this requests that
the QOS in the corresponding direction is not changed. This
may be used when requesting a QOS change in one direction
only, or when requesting a change only in the ProviderSpecific
part of a QOS specification and not in the SendingFlowspec or
the ReceivingFlowspec.
SERVICE_IMMEDIATE_TRAFFIC_CONTROL
In either a Sending or Receiving flowspec, this may be
combined using bit-wise OR with one of the other defined
ServiceType values to request the service provider to activate
traffic control coincident with provision of the flowspec.
16 New Concepts, Additions and Changes
MaxSduSize The maximum packet size, in bytes, that is permitted or used in the
traffic flow.
MinimumPolicedSize The minimum packet size that will be given the level of service
requested.
WinSock 2 introduces the notion of a socket group as a means for an application (or cooperating set of
applications) to indicate to an underlying service provider that a particular set of sockets are related and that
the group thus formed has certain attributes. Group attributes include relative priorities of the individual
sockets within the group and a group quality of service specification.
Applications needing to exchange multimedia streams over the network are benefited by being able to
establish a specific relationship among the set of sockets being utilized. As a minimum this might include a
New Concepts, Additions and Changes 17
hint to the service provider about the relative priorities of the media streams being carried. For example, a
conferencing application would want to have the socket used for carrying the audio stream be given higher
priority than that of the socket used for the video stream. Furthermore, there are transport providers (e.g.
digital telephony and ATM) which can utilize a group quality of service specification to determine the
appropriate characteristics for the underlying call or circuit connection. The sockets within a group are then
multiplexed in the usual manner over this call. By allowing the application to identify the sockets that make
up a group and to specify the required group attributes, such service providers can operate with maximum
effectiveness.
WSASocket() and WSAAccept() are two new functions used to explicitly create and/or join a socket group
coincident with creating a new socket. Socket group IDs can be retrieved by using getsockopt() with
option SO_GROUP_ID. Relative priority can be accessed by using get/setsockopt() with option
SO_GROUP_PRIORITY.
The two (or more) descriptors that reference a shared socket may be used independently as far as I/O is
concerned. However, the WinSock interface does not implement any type of access control, so it is up to
the processes involved to coordinate their operations on a shared socket. A typical use for shared sockets is
to have one process that is responsible for creating sockets and establishing connections, hand off sockets to
other processes which are responsible for information exchange.
Since what is duplicated are the socket descriptors and not the underlying socket, all of the state associated
with a socket is held in common across all the descriptors. For example a setsockopt() operation performed
using one descriptor is subsequently visible using a getsockopt() from any or all descriptors. A process
may call closesocket() on a duplicated socket and the descriptor will become deallocated. The underlying
socket, however, will remain open until closesocket() is called with the last remaining descriptor.
User-to-user data specified via parameters in WSAConnect() and/or the condition function of
WSAAccept() may be transferred to the peer during connection establishment, provided this feature is
supported by the service provider.
18 New Concepts, Additions and Changes
At connection teardown time, it is also possible (for protocols that support this) to exchange user data
between the endpoints. The end that initiates the teardown can call WSASendDisconnect() to indicate that
no more data is to be sent and cause the connection teardown sequence to be initiated. For certain
protocols, part of this teardown sequence is the delivery of disconnect data from the teardown initiator.
After receiving notice that the remote end has initiated the teardown sequence (typically via the FD_CLOSE
indication), the WSARecvDisconnect() function may be called to receive the disconnect data (if any).
To illustrate how disconnect data might be used, consider the following scenario. The client half of a
client/server application is responsible for terminating a socket connection. Coincident with the termination
it provides (via disconnect data) the total number of transactions it processed with the server. The server in
turn responds back with the cumulative grand total of transactions that it has processed with all clients. The
sequence of calls and indications might occur as follows:
Note that step (5’) must follow step (5), but has no timing relationship with step (6), (7), or (8).
When receiving into multiple buffers, completion occurs as data arrives from the network, regardless of
whether all of the supplied buffers are utilized.
New Concepts, Additions and Changes 19
Current multipoint implementations (e.g. IP multicast, ST-II, T.120, ATM UNI, etc.) vary widely with
respect to how nodes join a multipoint session, whether a particular node is designated as a central or root
node, and whether data is exchanged between all nodes or only between a root node and the various leaf
nodes. WinSock 2’s WSAPROTOCOL_INFO struct is used to declare the various multipoint attributes of
a protocol. By examining these attributes the programmer will know what conventions to follow with the
applicable WinSock 2 functions to setup, utilize and teardown multipoint sessions.
Note that the inclusion of these multipoint features in WinSock 2 does not preclude an application from
using an existing protocol-dependent interface, such as the Deering socket options for IP multicast (as
described in the TCP/IP section of the Windows Sockets 2 Protocol-Specific Annex).
Please refer to Appendix B. Multipoint and Multicast Semantics for detailed information on how the various
multipoint schemes are characterized and how the applicable features of WinSock 2 are utilized.
Because the SOCKET type is unsigned, compiling existing source code from, for example, a UNIX
environment may lead to compiler warnings about signed/unsigned data type mismatches.
This means, for example, that checking for errors when routines such as socket() or accept() return should
not be done by comparing the return value with -1, or seeing if the value is negative (both common, and
legal, approaches in BSD). Instead, an application should use the manifest constant INVALID_SOCKET
as defined in Winsock2.h. For example:
TYPICAL BSD STYLE:
s = socket(...);
if (s == -1) /* or s < 0 */
{...}
PREFERRED STYLE:
s = socket(...);
if (s == INVALID_SOCKET)
{...}
For compatibility with BSD, an application may choose to include a line of the form:
This will allow networking code which was written to use the global errno to work correctly in a single-
threaded environment. There are, obviously, some drawbacks. If a source file includes code which inspects
Windows Sockets Programming Considerations 25
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 WinSock the function WSASetLastError()
may be used for this purpose.)
PREFERRED STYLE:
r = recv(...);
if (r == -1 /* (but see below) */
&& WSAGetLastError() == EWOULDBLOCK)
{...}
Although error constants consistent with 4.3 Berkeley Sockets are provided for compatibility purposes,
applications should, where possible, use the "WSA" error code definitions. This is because error codes
returned by certain WinSock routines fall into the standard range of error codes as defined by Microsoft C.
Thus, a better version of the above source code fragment is:
r = recv(...);
if (r == -1 /* (but see below) */
&& WSAGetLastError() == WSAEWOULDBLOCK)
{...}
Note that this specification defines a recommended set of error codes, and lists the possible errors which
may be returned as a result of each function. It may be the case in some implementations that other
WinSock error codes will be returned in addition to those listed, and applications should be prepared to
handle errors other than those enumerated under each function description. However WinSock will
not return any value which is not enumerated in the table of legal WinSock errors given in Appendix A.1.
3.1.4. Pointers
All pointers used by applications with WinSock should be FAR, although this is only relevant to 16-bit
applications, and meaningless in a 32-bit operating system. To facilitate this, data type definitions such as
LPHOSTENT are provided.
The maximum number of sockets which a WinSock application can make use of is determined at the
application's compile time by the manifest constant FD_SETSIZE. This value is used in constructing the
fd_set structures used in select() (see section 4.16. ). The default value in Winsock2.h is 64. If an
application is designed to be capable of working with more than 64 sockets, the implementor should define
the manifest FD_SETSIZE in every source file before including Winsock2.h. One way of doing this may
be to include the definition within the compiler options in the makefile, for example adding -
DFD_SETSIZE=128 as an option to the compiler command line for Microsoft C. It must be emphasized
that defining FD_SETSIZE as a particular value has no effect on the actual number of sockets provided by a
WinSock service provider.
Consider an application which normally contacts a server on the TCP port corresponding to the "time"
service, but which provides a mechanism for the user to specify that an alternative port is to be used. The
Windows Sockets Programming Considerations 27
port number returned by getservbyname() is already in network order, which is the format required for
constructing an address, so no translation is required. However if the user elects to use a different port,
entered as an integer, the application must convert this from host to TCP/IP network order (using the
WSAHtons() function) before using it to construct an address. Conversely, if the application wishes to
display the number of the port within an address (returned via, e.g., getpeername()), the port number must
be converted from network to host order (using WSANtohs()) before it can be displayed.
Since the Intel Architecture and Internet byte orders are different, the conversions described above are
unavoidable. Application writers are cautioned that they should use the standard conversion functions
provided as part of WinSock rather than writing their own conversion code, since future implementations of
WinSock are likely to run on systems for which the host order is identical to the network byte order. Only
applications which use the standard conversion functions are likely to be portable.
3.3. WinSock 1.1 Compatibility Issues
To provide smooth backwards compatibility, WinSock 2 continues to support all of the WinSock 1.1
semantics and function calls except for those dealing with psuedo blocking. Since WinSock 2 runs only in
32 bit preemptively scheduled environments such as Windows NT and Windows 95, there is no need to
implement the psuedo blocking found in WinSock 1.1. This means that the WSAEINPROGRESS error
code will never be indicated and that the following WinSock 1.1 functions are not available to WinSock 2
applications:
1. WSACancelBlockingCall()
2. WSAIsBlocking()
3. WSASetBlockingHook()
4. WSAUnhookBlockingHook()
WinSock 1.1 programs that are written to utilize psuedo blocking will continue to operate correctly since
they link to either WINSOCK.DLL or WSOCK32.DLL, both of which continue to support the complete set
of WinSock 1.1 functions. In order for these programs to become WinSock 2 applications, some amount of
code modification must occur. In most cases, judicious use of threads to accommodate processing that was
being accomplished via a blocking hook function will suffice.
Even on a blocking socket, some operations (e.g. bind(), getsockopt(), getpeername()) can be completed
immediately. For such operations there is no difference between blocking and non-blocking operation.
Other operations (e.g. recv()) may be completed immediately or may take an arbitrary time to complete,
depending on various transport conditions. When applied to a blocking socket, these operations are
referred to as blocking operations.
With a (16-bit) WinSock 1.1, a blocking operation which cannot be completed immediately is handled via
psuedo blocking as follows. The service provider initiates the operation, and then enters a loop in which it
dispatches any Windows messages (yielding the processor to another thread if necessary) and then checks
for the completion of the WinSock function. If the function has completed, or if
WSACancelBlockingCall() has been invoked, the blocking function completes with an appropriate result.
Refer to WSASetBlockingHook() for a complete description of this mechanism, including pseudo code for
the various functions.
A service provider must allow installation of a blocking hook function that does not process messages in
order to avoid the possibility of reentrant messages while a blocking operation is outstanding. The simplest
such blocking hook function would simply return FALSE. If a service provider depends on messages for
internal operation it may execute PeekMessage(hMyWnd...) before executing the application blocking hook
so it can get its messages without affecting the rest of the system.
In (16-bit) WinSock 1.1 environments, if a Windows message is received for a process for which a blocking
operation is in progress, there is a risk that the application will attempt to issue another WinSock call.
Because of the difficulty of managing this condition safely, the WinSock 1.1 specification did not support
such application behavior. In WinSock 1.1, it was not permissible for an application to make multiple
nested Windows Sockets function calls. Only one outstanding function call was allowed for a particular
task. The only exceptions being two functions that were provided to assist the programmer in this situation.
WSAIsBlocking() may be called at any time to determine whether or not a blocking WinSock 1.1 call is in
progress. Similarly, WSACancelBlockingCall() may be called at any time to cancel an in-progress
blocking call, if any. Any other nesting of functions in WinSock 1.1 will fail with the error
WSAEINPROGRESS.
It should be emphasized that this restriction applies to both blocking and non-blocking operations, but only
for WinSock 1.1. For WinSock 2 applications (i.e., those that negotiate version 2.0 or higher at the time of
WSAStartup()) there is no restriction on the nesting of operations. Operations can become nested under
some rare circumstances such as during a WSAAccept() conditional-acceptance callback, or if a service
provider in turn invokes a WinSock 2 function.
Although this mechanism is sufficient for simple applications, it cannot support the complex message-
dispatching requirements of more advanced applications (for example, those using the MDI model). For
such applications, the WinSock 1.1 API included the function WSASetBlockingHook(), which allows the
application to specify a special routine that would be called instead of the default message dispatch routine
described above.
The WinSock provider calls the blocking hook only if all of the following are true: the routine is one which
is defined as being able to block, the specified socket is a blocking socket, and the request cannot be
completed immediately. (A socket is set to blocking by default, but the IOCTL FIONBIO, and
WSAAsyncSelect()set a socket to nonblocking mode.) If a WinSock 1.1 application uses only non-
blocking sockets and uses the WSAAsyncSelect() and/or the WSAAsyncGetXByY() routines instead of
select() and the getXbyY() routines, then the blocking hook will never be called and the application does
not need to be concerned with the reentrancy issues the blocking hook can introduce.
If a WinSock 1.1 application invokes an asynchronous or non-blocking operation which takes a pointer to a
memory object (e.g. a buffer, or a global variable) as an argument, it is the responsibility of the application
Windows Sockets Programming Considerations 29
to ensure that the object is available to WinSock throughout the operation. The application must not invoke
any Windows function which might affect the mapping or addressability of the memory involved.
It is important to distinguish the difference between shutting down a socket connection and closing a socket.
Shutting down a socket connection involves an exchange of protocol messages between the two endpoints
which is hereafter referred to as a shutdown sequence. Two general classes of shutdown sequences are
defined: graceful and abortive (also referred to as “hard”). In a graceful shutdown sequence, any data that
has been queued but not yet transmitted can be sent prior to the connection being closed. In an abortive
shutdown, any unsent data is lost. The occurrence of a shutdown sequence (graceful or abortive) can also
be used to provide an FD_CLOSE indication to the associated applications signifying that a shutdown is in
progress. Closing a socket, on the other hand, causes the socket handle to become deallocated so that the
application can no longer reference or use the socket in any manner.
In Windows Sockets, both the shutdown() function, and the WSASendDisconnect() function can be used
to initiate a shutdown sequence, while the closesocket() function is used to deallocate socket handles and
free up any associated resources. Some amount of confusion arises, however, from the fact that the
closesocket() function will implicitly cause a shutdown sequence to occur if it has not already happened. In
fact, it has become a rather common programming practice to rely on this feature and use closesocket() to
both initiate the shutdown sequence and deallocate the socket handle.
To facilitate this usage, the sockets interface provides for controls via the socket option mechanism that
allows the programmer to indicate whether the implicit shutdown sequence should be graceful or abortive,
and also whether the closesocket() function should linger (i.e. not complete immediately) to allow time for a
graceful shutdown sequence to complete. Provided that the programmer fully understands the ramifications
of using closesocket() in this manner, all is well. Unfortunately, many do not.
By establishing appropriate values for the socket options SO_LINGER and SO_DONTLINGER, the
following types of behavior can be obtained with the closesocket() function.
• Abortive shutdown sequence, immediate return from closesocket().
• Graceful shutdown, delay return until either shutdown sequence completes or a specified time
interval elapses. If the time interval expires before the graceful shutdown sequence completes, an
abortive shutdown sequence occurs and closesocket() returns.
• Graceful shutdown, return immediately and allow the shutdown sequence to complete in the
background. This is the default behavior. Note, however, that the application has no way of
knowing when (or whether) the graceful shutdown sequence completes.
One technique that can be used to minimize the chance of problems occurring during connection teardown
is to not rely on an implicit shutdown being initiated by closesocket(). Instead one of the two explicit
shutdown functions ( shutdown() or WSASendDisconnect() ) are used. This in turn will cause an
FD_CLOSE indication to be received by the peer application indicating that all pending data has been
received. To illustrate this, the following table shows the functions that would be invoked by the client and
server components of an application, where the client is responsible for initiating a graceful shutdown.
30 Windows Sockets Programming Considerations
Note that the timing sequence is maintained from step (1) to step (6) between the client
and the server, except for step (4’) and (5’) which only has local timing significance in the
sense that step (5) follows step (5’) on the client side while step (4’) follows step (4) on
the server side, with no timing relationship with the remote party.
A user can determine if there is any OOB data waiting to be read using the ioctlsocket(SIOCATMARK)
function (q.v.). For protocols where the concept of the "position" of the OOB data block within the normal
data stream is meaningful (i.e. TCP), a Windows Sockets service provider will maintain a conceptual
"marker" indicating the position of the last byte of OOB data within the normal data stream. This is not
necessary for the implementation of the ioctlsocket(SIOCATMARK) functionality - the presence or
absence of OOB data is all that is required.
For protocols where the concept of the "position" of the OOB data block within the normal data stream is
meaningful an application may prefer to process out-of-band data "in-line", as part of the normal data
stream. This is achieved by setting the socket option SO_OOBINLINE (see section 4.19. , setsockopt()).
For other protocols where the OOB data blocks are truly independent of the normal data stream, attempting
to set SO_OOBINLINE will result in an error. An application can use the SIOCATMARK ioctlsocket()
command (see section 4.10. ) to determine whether there is any unread OOB data preceding the mark. For
example, it might use this to resynchronize with its peer by ensuring that all data up to the mark in the data
stream is discarded when appropriate.
Windows Sockets Programming Considerations 31
Specifically, the TCP urgent pointer in BSD points to the byte after the urgent data byte, and an RFC-
compliant TCP urgent pointer points to the urgent data byte. As a result, if an application sends urgent data
from a BSD-compatible implementation to an RFC-1122 compatible implementation then the receiver will
read the wrong urgent data byte (it will read the byte located after the correct byte in the data stream as the
urgent data byte).
To minimize interoperability problems, applications writers are advised not to use out-of-band data unless
this is required in order to interoperate with an existing service. Windows Sockets suppliers are urged to
document the out-of-band semantics (BSD or RFC 1122) which their product implements.
Arrival of a TCP segment with the "URG"ent flag set indicates the existence of a single byte of "OOB" data
within the TCP data stream. The "OOB data block" is one byte in size. The urgent pointer is a positive
32 Windows Sockets Programming Considerations
offset from the current sequence number in the TCP header that indicates the location of the "OOB data
block" (ambiguously, as noted above). This may point to data that has not yet been received.
With SO_OOBINLINE disabled (the default), when the TCP segment containing the byte pointed to by the
urgent pointer arrives, the OOB data block (one byte) is removed from the data stream and buffered. If a
subsequent TCP segment arrives with the urgent flag set (and a new urgent pointer), the OOB byte currently
queued may be lost as it is replaced by the new OOB data block (as occurs in Berkeley Software
Distribution). It is never replaced in the data stream, however.
With SO_OOBINLINE enabled, the urgent data remains in the data stream. As a result, the OOB data
block is never lost when a new TCP segment arrives containing urgent data. The existing OOB data "mark"
is updated to the new position.
Note: the getXbyY() and WSAAsyncGetXbyY() functions now appear in section 5 on name
resolution.
In each routine it is indicated that the header file winsock2.h must be included. Appendix A.2 lists the
Berkeley-compatible header files which are supported. These are provided for compatibility purposes only,
and each of them will simply include winsock2.h. The Windows header file windows.h is also needed, but
winsock2.h will include it if necessary.
4.1. accept()
Description Accept a connection on a socket.
#include <winsock2.h>
SOCKET WSAAPI
accept (
IN SOCKET s,
OUT struct sockaddr FAR* addr,
OUT int FAR* addrlen
);
Remarks This routine extracts the first connection on the queue of pending connections on s,
creates a new socket and returns a handle to the new socket. The newly created socket has
the same properties as s including asynchronous events registered with
WSAAsyncSelect() or with WSAEventSelect(), but not including the listening socket’s
group ID, if any. If no pending connections are present on the queue, and the socket is not
marked as non-blocking, accept() blocks the caller until a connection is present.
If the socket is marked non-blocking and no pending connections are present on the
queue, accept() returns a failure with the error WSAEWOULDBLOCK, as described
below.
After accept succeeds, and returns a new socket handle, the accepted socket may not be
used to accept more connections. The original socket remains open, and listening for new
connection requests.
The argument addr is a result parameter that is filled in with the address of the connecting
entity, as known to the communications layer. The exact format of the addr parameter is
determined by the address family in which the communication is occurring. The addrlen
accept 37
Return Value If no error occurs, accept() returns a value of type SOCKET which is a descriptor for the
accepted socket. Otherwise, a value of INVALID_SOCKET is returned, and a specific
error code may be retrieved by calling WSAGetLastError().
The integer referred to by addrlen initially contains the amount of space pointed to by
addr. On return it will contain the actual length in bytes of the address returned.
4.2. bind()
Description Associate a local address with a socket.
#include <winsock2.h>
int WSAAPI
bind (
IN SOCKET s,
IN const struct sockaddr FAR* name,
IN int namelen
);
name The address to assign to the socket. The sockaddr structure is defined as
follows:
struct sockaddr {
u_short sa_family;
char sa_data[14];
};
Except for the sa_family field, sockaddr contents are expressed
in network byte order. NOTE: In WinSock 2, the name parameter
is not strictly interpreted as a pointer to a "sockaddr" struct. It is cast
this way for Windows Sockets compatibility. The actual structure is
interpreted differently in the context of different address families. The
only requirements are that the first u_short is the address family and the
total size of the memory buffer in bytes is namelen
As an example, in the Internet address family, a name consists of three parts: the address
family, a host address, and a port number which identifies the application. In WinSock 2,
the name parameter is not strictly interpreted as a pointer to a "sockaddr" struct. It is cast
this way for Windows Sockets compatibility. Service Providers are free to regard it as a
pointer to a block of memory of size namelen. The first two bytes in this block
(corresponding to "sa_family" in the "sockaddr" declaration) must contain the address
family that was used to create the socket. Otherwise an error WSAEFAULT will occur.
If an application does not care what local address is assigned to it, it may specify the
manifest constant value ADDR_ANY for the sa_data field of the name parameter. This
allows the underlying service provider to use any appropriate network address, potentially
simplifying application programming in the presence of multi-homed hosts (i.e., hosts that
have more than one network interface and address). For TCP/IP, if the port is specified
as 0, the service provider will assign a unique port to the application with a value between
1024 and 5000. The application may use getsockname() after bind() to learn the address
and the port that has been assigned to it, but note that if the Internet address is equal to
INADDR_ANY, getsockname() will not necessarily be able to supply the address until
bind 39
the socket is connected, since several addresses may be valid if the host is multi-homed.
Binding to a specific port number (i.e., other than port 0) is discouraged for client
applications, since there is a danger of conflicting with another socket that is already
using that port number.
Return Value If no error occurs, bind() returns 0. Otherwise, it returns SOCKET_ERROR, and a
specific error code may be retrieved by calling WSAGetLastError().
4.3. closesocket()
Description Close a socket.
#include <winsock2.h>
int WSAAPI
closesocket (
IN SOCKET s
);
Remarks This function closes a socket. More precisely, it releases the socket descriptor s, so that
further references to s will fail with the error WSAENOTSOCK. If this is the last
reference to an underlying socket, the associated naming information and queued data are
discarded. Any pending blocking or asynchronous calls issued by any thread in this
process are canceled without posting any notification messages. Any pending overlapped
operations (e.g.,
WSASend()/WSASendTo()/WSARecv()/WSARecvFrom()/WSAIoctl() with an
overlapped socket) issued by any thread in this process are also canceled. Whatever
completion action was specified for these overlapped operations is performed (e.g., event,
completion routine, or completion port). In this case, the pending overlapped operations
fail with the error status WSA_OPERATION_ABORTED. An application should always
have a matching call to closesocket() for each successful call to socket() to return socket
resources to the system.
The semantics of closesocket() are affected by the socket options SO_LINGER and
SO_DONTLINGER as follows (Note: by default SO_DONTLINGER is enabled - that is,
SO_LINGER is disabled):
If SO_LINGER is set (i.e. the l_onoff field of the linger structure is non-zero; see sections
4.7. and 4.19. ) with a zero timeout interval (l_linger is zero), closesocket() is not
blocked even if queued data has not yet been sent or acknowledged. This is called a
"hard" or "abortive" close, because the socket's virtual circuit is reset immediately, and
any unsent data is lost. Any recv() call on the remote side of the circuit will fail with
WSAECONNRESET.
socket, although closesocket() may continue to fail unless the application disables
SO_DONTLINGER, enables SO_LINGER with a zero timeout, or calls shutdown() to
initiate closure.
If SO_DONTLINGER is set on a stream socket (i.e. the l_onoff field of the linger
structure is zero; see sections 4.7. and 4.19. ), the closesocket() call will return
immediately and does not get WSAEWOULDBLOCK, whether the socket is blocking or
non-blocking. However, any data queued for transmission will be sent if possible before
the underlying socket is closed. This is also called a graceful disconnect. Note that in
this case the WinSock provider may not release the socket and other resources for an
arbitrary period, which may affect applications which expect to use all available sockets.
This is the default behavior (SO_DONTLINGER is set by default).
Note: to assure that all data is sent and received on a connection, an application should
call shutdown() before calling closesocket() (see section 3.4. Graceful shutdown, linger
options and socket closure for more information). Also note, FD_CLOSE will not be
posted after closesocket() is called.
For additional information please see 3.4. Graceful shutdown, linger options and socket
closure.
4.4. connect()
Description Establish a connection to a peer.
#include <winsock2.h>
int WSAAPI
connect (
IN SOCKET s,
IN const struct sockaddr FAR* name,
IN int namelen
);
Remarks This function is used to create a connection to the specified destination. If the socket, s, is
unbound, unique values are assigned to the local association by the system, and the socket
is marked as bound.
For connectionless sockets, name may indicate any valid address, including a broadcast
address. However, to connect to a broadcast address, a socket must have setsockopt()
connect 43
SO_BROADCAST enabled, otherwise connect() will fail with the error code
WSAEACCES.
Comments When connected sockets break (i.e. become closed for whatever reason), they should be
discarded and recreated. It is safest to assume that when things go awry for any reason
on a connected socket, the application must discard and recreate the needed sockets in
order to return to a stable point.
Return Value If no error occurs, connect() returns 0. Otherwise, it returns SOCKET_ERROR, and a
specific error code may be retrieved by calling WSAGetLastError().
On a blocking socket, the return value indicates success or failure of the connection
attempt.
With a non-blocking socket, the connection attempt may not be completed immediately -
in this case connect() will return SOCKET_ERROR, and WSAGetLastError() will
return WSAEWOULDBLOCK. In this case the application may:
1. Use select() to determine the completion of the connection request by checking if the
socket is writeable, or
For a non-blocking socket, until the connection attempt completes, all subsequent calls to
connect() on the same socket will fail with the error code WSAEALREADY, and
WSAEISCONN when the connection completes successfully. Due to ambiguities in
version 1.1 of the Windows Sockets specification, error codes returned from connect()
while a connection is already pending may vary among implementations. As a result, it
isn’t recommended that applications use multiple calls to connect() to detect connection
completion. If they do, they must be prepared to handle WSAEINVAL and
WSAEWOULDBLOCK error values the same way that they handle WSAEALREADY,
to assure robust execution.
If the return error code indicates the connection attempt failed (i.e.
WSAECONNREFUSED, WSAENETUNREACH, WSAETIMEDOUT) the application
may call connect() again for the same socket.
4.5. getpeername()
Description Get the address of the peer to which a socket is connected.
#include <winsock2.h>
int WSAAPI
getpeername (
IN SOCKET s,
OUT struct sockaddr FAR* name,
IN OUT int FAR* namelen
);
Remarks getpeername() retrieves the name of the peer connected to the socket s and stores it in the
struct sockaddr identified by name. It may be used only on a connected socket. For
datagram sockets, only the name of a peer specified in a previous connect() call will be
returned - any name specified by a previous sendto() call will not be returned by
getpeername().
On call, the namelen argument contains the size of the name buffer in bytes. On return,
the namelen argument contains the actual size of the name returned in bytes.
4.6. getsockname()
Description Get the local name for a socket.
#include <winsock2.h>
int WSAAPI
getsockname (
IN SOCKET s,
OUT struct sockaddr FAR* name,
IN OUT int FAR* namelen
);
Remarks getsockname() retrieves the current name for the specified socket descriptor in name. It
is used on a bound and/or connected socket specified by the s parameter. The local
association is returned. This call is especially useful when a connect() call has been
made without doing a bind() first; this call provides the only means by which you can
determine the local association which has been set by the system.
On call, the namelen argument contains the size of the name buffer in bytes. On return,
the namelen argument contains the actual size of the name returned in bytes.
If a socket was bound to an unspecified address (e.g., ADDR_ANY), indicating that any
of the host's addresses within the specified address family should be used for the socket,
getsockname() will not necessarily return information about the host address, unless the
socket has been connected with connect() or accept(). A WinSock application must not
assume that the address will be specified unless the socket is connected. This is because
for a multi-homed host the address that will be used for the socket is unknown unless the
socket is connected. If the socket is using a connectionless protocol, the address may not
be available until I/O occurs on the socket.
4.7. getsockopt()
Description Retrieve a socket option.
#include <winsock2.h>
int WSAAPI
getsockopt (
IN SOCKET s,
IN int level,
IN int optname,
OUT char FAR* optval,
IN OUT int FAR* optlen
);
level The level at which the option is defined; the supported levels include
SOL_SOCKET and IPPROTO_TCP. (See annex for more protocol-
specific levels.)
optval A pointer to the buffer in which the value for the requested option is to
be returned.
Remarks getsockopt() retrieves the current value for a socket option associated with a socket of
any type, in any state, and stores the result in optval. Options may exist at multiple
protocol levels, but they are always present at the uppermost "socket'' level. Options
affect socket operations, such as the routing of packets, out-of-band data transfer, etc.
The value associated with the selected option is returned in the buffer optval. The integer
pointed to by optlen should originally contain the size of this buffer; on return, it will be
set to the size of the value returned. For SO_LINGER, this will be the size of a struct
linger; for most other options it will be the size of an integer.
The application is responsible for allocating any memory space pointed to directly or
indirectly by any of the parameters it specified.
If the option was never set with setsockopt(), then getsockopt() returns the default value
for the option.
The following options are supported for getsockopt(). The Type identifies the type of data
addressed by optval (NOTE: there are other protocol-specific options available, as described in the
Windows Sockets 2 Protocol Specific Annex).
Level =
SOL_SOCKET
Value Type Meaning Default
SO_ACCEPTCONN BOOL Socket is listen()ing. FALSE unless a
WSPListen() has
been performed
50 getsockopt
level =
IPPROTO_TCP
SO_DEBUG
WinSock service providers are encouraged (but not required) to supply output debug
information if the SO_DEBUG option is set by an application. The mechanism for
generating the debug information and the form it takes are beyond the scope of this
specification.
SO_ERROR
The SO_ERROR option returns and resets the per-socket based error code, which is
different from the per-thread based error code that is handled using the
WSAGetLastError() and WSASetLastError() function calls. A successful call using
the socket does not reset the socket based error code returned by the SO_ERROR option.
SO_GROUP_ID
Reserved for future use with socket groups: This is a get-only socket option which
indicates the identifier of the group this socket belongs to. Note that socket group IDs are
unique across all processes for a given service provider. If this socket is not a group
socket, the value is NULL.
SO_GROUP_PRIORITY
Reserved for future use with socket groups: Group priority indicates the priority of the
specified socket relative to other sockets within the socket group. Values are non-
negative integers, with zero corresponding to the highest priority. Priority values
represent a hint to the underlying service provider about how potentially scarce resources
should be allocated. For example, whenever two or more sockets are both ready to
transmit data, the highest priority socket (lowest value for SO_GROUP_PRIORITY)
52 getsockopt
should be serviced first, with the remainder serviced in turn according to their relative
priorities.
The WSAENOPROTOOPT error code is indicated for non group sockets or for service
providers which do not support group sockets.
SO_KEEPALIVE
An application may request that a TCP/IP service provider enable the use of "keep-alive"
packets on TCP connections by turning on the SO_KEEPALIVE socket option. A
WinSock provider need not support the use of keep-alive: if it does, the precise semantics
are implementation-specific but should conform to section 4.2.3.6 of RFC 1122:
Requirements for Internet Hosts -- Communication Layers. If a connection is dropped as
the result of "keep-alives" the error code WSAENETRESET is returned to any calls in
progress on the socket, and any subsequent calls will fail with WSAENOTCONN.
SO_LINGER
SO_LINGER controls the action taken when unsent data is queued on a socket and a
closesocket() is performed. See closesocket() for a description of the way in which the
SO_LINGER settings affect the semantics of closesocket(). The application gets the
current behavior by retrieving a struct linger (pointed to by the optval argument) with the
following elements:
struct linger {
u_short l_onoff;
u_short l_linger;
}
SO_MAX_MSG_SIZE
This is a get-only socket option which indicates the maximum outbound (send) size of a
message for message-oriented socket types (e.g., SOCK_DGRAM) as implemented by a
particular service provider. It has no meaning for byte stream oriented sockets. There is
no provision to find out the maximum inbound message size.
SO_PROTOCOL_INFO
This is a get-only option which supplies the WSAPROTOCOL_INFO structure
associated with this socket. See WSAEnumProtocols() for more information about this
structure.
SO_RCVBUF
SO_SNDBUF
When a Windows Sockets implementation supports the SO_RCVBUF and SO_SNDBUF
options, an application may request different buffer sizes (larger or smaller). The call to
setsockopt() may succeed although the implementation did not provide the whole amount
requested. An application must call this function with the same option to check the buffer
size actually provided.
SO_REUSEADDR
By default, a socket may not be bound (see bind()) to a local address which is already in
use. On occasions, however, it may be desirable to "re-use" an address in this way. Since
every connection is uniquely identified by the combination of local and remote addresses,
there is no problem with having two sockets bound to the same local address as long as
the remote addresses are different. To inform the WinSock provider that a bind() on a
socket should not be disallowed because the desired address is already in use by another
socket, the application should set the SO_REUSEADDR socket option for the socket
before issuing the bind(). Note that the option is interpreted only at the time of the
getsockopt 53
bind(): it is therefore unnecessary (but harmless) to set the option on a socket which is not
to be bound to an existing address, and setting or resetting the option after the bind() has
no effect on this or any other socket.
PVD_CONFIG
This option retrieves an "opaque" data structure object from the service provider
associated with socket s. This object stores the current configuration information of the
service provider. The exact format of this data structure is service provider specific.
TCP_NODELAY
The Nagle algorithm is disabled if the TCP_NODELAY option is enabled (and vice
versa.). The Nagle algorithm (described in RFC 896) is very effective in reducing the
number of small packets sent by a host by essentially buffering send data if there is
unacknowledged data already "in flight" or until a full-size packet can be sent. It is highly
recommended that Windows Sockets implementations enable the Nagle Algorithm by
default, and for the vast majority of application protocols the Nagle Algorithm can deliver
significant performance enhancements. However, for some applications this algorithm can
impede performance, and setsockopt() with the same option may be used to turn it off.
These are applications where many small messages are sent, which need to be received by
the peer with the time delays between the messages maintained.
4.8. htonl()
Description Convert a u_long from host to TCP/IP network byte order (which is big-endian).
#include <winsock2.h>
u_long WSAAPI
htonl (
IN u_long hostlong
);
Remarks This routine takes a 32-bit number in host byte order and returns a 32-bit number in the
network byte order used in TCP/IP networks.
Return Value htonl() returns the value in TCP/IP’s network byte order.
4.9. htons()
Description Convert a u_short from host to TCP/IP network byte order (which is big-endian).
.
#include <winsock2.h>
u_short WSAAPI
htons (
IN u_short hostshort
);
Remarks This routine takes a 16-bit number in host byte order and returns a 16-bit number in
network byte order used in TCP/IP networks.
Return Value htons() returns the value in TCP/IP network byte order.
4.10. ioctlsocket()
Description Control the mode of a socket.
#include <winsock2.h>
int WSAAPI
ioctlsocket (
IN SOCKET s,
IN long cmd,
IN OUT u_long FAR* argp
);
Remarks This routine may be used on any socket in any state. It is used to get or retrieve operating
parameters associated with the socket, independent of the protocol and communications
subsystem. The following commands are supported:
Command Semantics
FIONREAD Determine the amount of data which can be read atomically from socket
s. argp points to an unsigned long in which ioctlsocket() stores the
result. If s is stream-oriented (e.g., type SOCK_STREAM),
FIONREAD returns an amount of data which may be read in a single
recv(); this may or may not be the same as the total amount of data
queued on the socket. If s is message-oriented (e.g., type
SOCK_DGRAM), FIONREAD returns the size of the first datagram
(message) queued on the socket.
SIOCATMARK Determine whether or not all out-of-band data has been read (See
section 3.5.2 OOB Data in TCP for a discussion of this topic.). This
applies only to a socket of stream style (e.g., type SOCK_STREAM)
which has been configured for in-line reception of any out-of-band data
ioctlsocket 57
Compatibility This function is a subset of ioctl() as used in Berkeley sockets. In particular, there is no
command which is equivalent to FIOASYNC, while SIOCATMARK is the only socket-
level command which is supported.
Return Value Upon successful completion, the ioctlsocket() returns 0. Otherwise, a value of
SOCKET_ERROR is returned, and a specific error code may be retrieved by calling
WSAGetLastError().
4.11. listen()
Description Establish a socket to listen for incoming connection.
#include <winsock2.h>
int WSAAPI
listen (
IN SOCKET s,
IN int backlog
);
backlog The maximum length to which the queue of pending connections may
grow. If this value is SOMAXCONN, then the underlying service
provider responsible for socket s will set the backlog to a maximum
“reasonable” value. There is no standard provision to find out the actual
backlog value used.
Remarks To accept connections, a socket is first created with socket(), bound to a local address
with bind(), a backlog for incoming connections is specified with listen(), and then the
connections are accepted with accept(). listen() applies only to sockets that are
connection-oriented , e.g., those of type SOCK_STREAM. The socket s is put into
"passive'' mode where incoming connection requests are acknowledged and queued
pending acceptance by the process.
This function is typically used by servers that could have more than one connection
request at a time: if a connection request arrives with the queue full, the client will receive
an error with an indication of WSAECONNREFUSED.
listen() attempts to continue to function rationally when there are no available descriptors.
It will accept connections until the queue is emptied. If descriptors become available, a
later call to listen() or accept() will re-fill the queue to the current or most recent
"backlog'', if possible, and resume listening for incoming connections.
An application may call listen() more than once on the same socket. This has the effect of
updating the current backlog for the listening socket. Should there be more pending
connections than the new backlog value, the excess pending connections will be reset and
dropped.
Compatibility backlog is limited (silently) to a reasonable value as determined by the underlying service
provider. Illegal values are replaced by the nearest legal value. There is no standard
provision to find out the actual backlog value used.
4.12. ntohl()
Description Convert a u_long from TCP/IP network order to host byte order (which is big-endian).
#include <winsock2.h>
u_long WSAAPI
ntohl (
IN u_long netlong
);
Remarks This routine takes a 32-bit number in TCP/IP network byte order and returns a 32-bit
number in host byte order.
4.13. ntohs()
Description Convert a u_short from TCP/IP network byte order to host byte order (which is big-
endian).
#include <winsock2.h>
u_short WSAAPI
ntohs (
IN u_short netshort
);
Remarks This routine takes a 16-bit number in TCP/IP network byte order and returns a 16-bit
number in host byte order.
4.14. recv()
Description Receive data from a connected socket.
#include <winsock2.h>
int WSAAPI
recv (
IN SOCKET s,
OUT char FAR* buf,
IN int len,
IN int flags
);
Remarks This function is used on connected sockets or bound connectionless sockets specified by
the s parameter and is used to read incoming data. The socket’s local address must be
known. For server applications, this is usually done explicitly through bind() or
implicitly through accept() or WSAAccept(). Explicit binding is discouraged for client
applications. For client applications the socket can become bound implicitly to a local
address through connect(), WSAConnect(), sendto(), WSASendTo(), or
WSAJoinLeaf().
For connected, connectionless sockets, this function restricts the addresses from which
received messages are accepted. The function only returns messages from the remote
address specified in the connection. Messages from other addresses are (silently)
discarded.
For byte stream style socket (e.g., type SOCK_STREAM), as much information as is
currently available up to the size of the buffer supplied is returned. If the socket has been
configured for in-line reception of out-of-band data (socket option SO_OOBINLINE) and
out-of-band data is unread, only out-of-band data will be returned. The application may
use the ioctlsocket() or WSAIoctl() with the SIOCATMARK command to determine
whether any more out-of-band data remains to be read.
For message-oriented sockets (e.g., type SOCK_DGRAM), data is extracted from the first
enqueued datagram (message) from the destination address specified in the connect()
call. If the datagram or message is larger than the buffer supplied, the buffer is filled with
the first part of the datagram, and recv() generates the error WSAEMSGSIZE. For
unreliable protocols (e.g. UDP) the excess data is lost, for reliable protocols the data is
retained by the service provider until it is successfully read by calling recv() with a large
enough buffer. For TCP/IP, an application cannot receive from any multicast address until
after becoming a group member (see Windows Sockets 2 Protocol-Specific Annex for
more information).
If no incoming data is available at the socket, the recv() call blocks and waits for data to
arrive according to the blocking rules defined for WSARecv() with the MSG_PARTIAL
flag not set unless the socket is non-blocking. In this case a value of SOCKET_ERROR
recv 63
If the socket is connection-oriented and the remote side has shut down the connection
gracefully, and all data has been received already, a recv() will complete immediately
with 0 bytes received. If the connection has been reset, a recv() will fail with the error
WSAECONNRESET.
Flags may be used to influence the behavior of the function invocation beyond the
options specified for the associated socket. That is, the semantics of this function are
determined by the socket options and the flags parameter. The latter is constructed by or-
ing any of the following values:
Value Meaning
MSG_PEEK Peek at the incoming data. The data is copied into the buffer but is not
removed from the input queue, and the function returns the number of
bytes currently pending to receive.
MSG_OOB Process out-of-band data (See section 3.5. Out-Of-Band data for a
discussion of this topic.)
Return Value If no error occurs, recv() returns the number of bytes received. If the connection has been
gracefully closed, and all data received, the return value is 0. Otherwise, a value of
SOCKET_ERROR is returned, and a specific error code may be retrieved by calling
WSAGetLastError().
WSAEMSGSIZE The message was too large to fit into the specified
buffer and was truncated.
WSAEINVAL The socket has not been bound (e.g., with bind()), or
an unknown flag was specified, or MSG_OOB was
specified for a socket with SO_OOBINLINE enabled
or (for byte stream sockets only) len was 0 or
negative.
4.15. recvfrom()
Description Receive a datagram and store the source address.
#include <winsock2.h>
int WSAAPI
recvfrom (
IN SOCKET s,
OUT char FAR* buf,
IN int len,
IN int flags,
OUT struct sockaddr FAR* from,
IN OUT int FAR* fromlen
);
from An optional pointer to a buffer which will hold the source address upon
return.
Remarks This function is used to read incoming data on a socket and capture the address from
which the data was sent. The socket must not be connected. The socket’s local address
must be known. For server applications, this is usually done explicitly through bind().
Explicit binding is discouraged for client applications. For client applications using this
function, the socket can become bound implicitly to a local address through sendto(),
WSASendTo(), or WSAJoinLeaf().
For message-oriented sockets, data is extracted from the first enqueued message, up to the
size of the buffer supplied. If the datagram or message is larger than the buffer supplied,
the buffer is filled with the first part of the datagram, and recvfrom() generates the error
WSAEMSGSIZE. For unreliable protocols (e.g. UDP) the excess data is lost.
If no incoming data is available at the socket, the recvfrom() call blocks and waits for
data to arrive according to the blocking rules defined for WSARecv() with the
MSG_PARTIAL flag not set unless the socket is non-blocking. In this case a value of
SOCKET_ERROR is returned with the error code set to WSAEWOULDBLOCK. The
select(), WSAAsyncSelect(), or WSAEventSelect() may be used to determine when
more data arrives.
If the socket is connection-oriented and the remote side has shut down the connection
gracefully, a recvfrom() will complete immediately with 0 bytes received. If the
connection has been reset recvfrom() will fail with the error WSAECONNRESET.
Flags may be used to influence the behavior of the function invocation beyond the
options specified for the associated socket. That is, the semantics of this function are
determined by the socket options and the flags parameter. The latter is constructed by or-
ing any of the following values:
Value Meaning
MSG_PEEK Peek at the incoming data. The data is copied into the buffer but is not
removed from the input queue, and the function returns the number of
bytes currently pending to receive
MSG_OOB Process out-of-band data (See section 3.5. Out-Of-Band data for a
discussion of this topic.)
Return Value If no error occurs, recvfrom() returns the number of bytes received. If the connection has
been gracefully closed, and all data received, the return value is 0. Otherwise, a value of
SOCKET_ERROR is returned, and a specific error code may be retrieved by calling
WSAGetLastError().
WSAEFAULT The buf or from parameters are not part of the user
address space, or the fromlen argument is too small to
accommodate the peer address.
WSAEINVAL The socket has not been bound (e.g., with bind()), or
an unknown flag was specified, or MSG_OOB was
specified for a socket with SO_OOBINLINE enabled,
or (for byte stream style sockets only) len was 0 or
negative.
recvfrom 67
WSAEMSGSIZE The message was too large to fit into the specified
buffer and was truncated.
4.16. select()
Description Determine the status of one or more sockets, waiting if necessary.
#include <winsock2.h>
int WSAAPI
select (
IN int nfds,
IN OUT fd_set FAR * readfds,
IN OUT fd_set FAR * writefds,
IN OUT fd_set FAR * exceptfds,
IN const struct timeval FAR * timeout
);
nfds This argument is ignored and included only for the sake of
compatibility.
timeout The maximum time for select() to wait, or NULL for blocking
operation.
Remarks This function is used to determine the status of one or more sockets. For each socket, the
caller may request information on read, write or error status. The set of sockets for which
a given status is requested is indicated by an fd_set structure. The sockets contained
within the fd_set structures must be associated with a single service provider. For the
purpose of this restriction, sockets are considered to be from the same service provider if
the WSAPROTOCOL_INFO structures describing their protocols have the same
providerId value.
Upon return, the structures are updated to reflect the subset of these sockets which meet
the specified condition, and select() returns the number of sockets meeting the conditions.
A set of macros is provided for manipulating an fd_set. These macros are compatible
with those used in the Berkeley software, but the underlying representation is completely
different.
The parameter readfds identifies those sockets which are to be checked for readability. If
the socket is currently listen()ing, it will be marked as readable if an incoming connection
request has been received, so that an accept() is guaranteed to complete without blocking.
For other sockets, readability means that queued data is available for reading so that a
recv() or recvfrom(), WSARecv() or WSARecvFrom(),is guaranteed not to block.
For connection-oriented sockets, readability may also indicate that a close request has
been received from the peer. If the virtual circuit was closed gracefully, and all data
received, then a recv() will return immediately with 0 bytes read. If the virtual circuit was
reset, then a recv() will complete immediately with an error code, such as
WSAECONNRESET. The presence of out-of-band data will be checked if the socket
option SO_OOBINLINE has been enabled (see setsockopt()).
select 69
The parameter writefds identifies those sockets which are to be checked for writability.
If a socket is connect()ing (non-blocking), writability means that the connection
establishment successfully completed. If the socket is not in the process of connect()ing,
writability means that a send() or sendto(), or WSASend() or WSASendto(), are
guaranteed to succeed. However, they may block on a blocking socket if the len exceeds
the amount of outgoing system buffer space available. [It is not specified how long these
guarantees can be assumed to be valid, particularly in a multithreaded environment.]
The parameter exceptfds identifies those sockets which are to be checked for the presence
of out-of-band data (see section 3.5. Out-Of-Band data for a discussion of this topic) or
any exceptional error conditions. Note that out-of-band data will only be reported in this
way if the option SO_OOBINLINE is FALSE. If a socket is connect()ing (non-blocking),
failure of the connect attempt is indicated in exceptfds (application must then call
getsockopt() SO_ERROR to determine the error value to describe why the failure
occurred. This specification does not define which other errors will be included.
Any two of readfds, writefds, or exceptfds may be given as NULL if no descriptors are to
be checked for the condition of interest. At least one must be non-NULL, and any non-
NULL descriptor set must contain at least one socket descriptor..
Summary: A socket will be identified in a particular set when select() returns if:
Four macros are defined in the header file winsock2.h for manipulating and checking the
descriptor sets. The variable FD_SETSIZE determines the maximum number of
descriptors in a set. (The default value of FD_SETSIZE is 64, which may be modified by
#defining FD_SETSIZE to another value before #including winsock2.h.) Internally,
socket handles in a fd_set are not represented as bit flags as in Berkeley Unix. Their data
representation is opaque. Use of these macros will maintain software portability between
different socket environments. The macros to manipulate and check fd_set contents are:
The parameter timeout controls how long the select() may take to complete. If timeout is
a null pointer, select() will block indefinitely until at least one descriptor meets the
specified criteria. Otherwise, timeout points to a struct timeval which specifies the
maximum time that select() should wait before returning. When select() returns, the
70 select
contents of the struct timeval are not altered. If the timeval is initialized to {0, 0}, select()
will return immediately; this is used to "poll" the state of the selected sockets. If this is
the case, then the select() call is considered nonblocking and the standard assumptions for
nonblocking calls apply. For example, the blocking hook will not be called, and WinSock
will not yield.
Return Value select() returns the total number of descriptors which are ready and contained in the
fd_set structures, 0 if the time limit expired, or SOCKET_ERROR if an error occurred. If
the return value is SOCKET_ERROR, WSAGetLastError() may be used to retrieve a
specific error code.
Comments select() has no effect on the persistence of socket events registered with
WSAAsyncSelect() or WSAEventSelect().
4.17. send()
Description Send data on a connected socket.
#include <winsock2.h>
int WSAAPI
send (
IN SOCKET s,
IN const char FAR * buf,
IN int len,
IN int flags
);
Remarks send() is used to write outgoing data on a connected socket. For message-oriented
sockets, care must be taken not to exceed the maximum packet size of the underlying
provider, which can be obtained by getting the value of socket option
SO_MAX_MSG_SIZE. If the data is too long to pass atomically through the underlying
protocol the error WSAEMSGSIZE is returned, and no data is transmitted.
Note that the successful completion of a send() does not indicate that the data was
successfully delivered.
If no buffer space is available within the transport system to hold the data to be
transmitted, send() will block unless the socket has been placed in a non-blocking I/O
mode. On non-blocking stream-oriented sockets, the number of bytes written may be
between 1 and the requested length, depending on buffer availability on both the local and
foreign hosts. The select(), WSAAsyncSelect() or WSAEventSelect() call may be used
to determine when it is possible to send more data.
Flags may be used to influence the behavior of the function invocation beyond the
options specified for the associated socket. That is, the semantics of this function are
determined by the socket options and the flags parameter. The latter is constructed by or-
ing any of the following values:
Value Meaning
MSG_DONTROUTE
Specifies that the data should not be subject to routing. A WinSock
service provider may choose to ignore this flag.
Return Value If no error occurs, send() returns the total number of bytes sent. (Note that this may be
less than the number indicated by len for non-blocking sockets.) Otherwise, a value of
SOCKET_ERROR is returned, and a specific error code may be retrieved by calling
WSAGetLastError().
WSAEHOSTUNREACH The remote host can't be reached from this host at this
time.
4.18. sendto()
Description Send data to a specific destination.
#include <winsock2.h>
int WSAAPI
sendto (
IN SOCKET s,
IN const char FAR * buf,
IN int len,
IN int flags,
IN const struct sockaddr FAR * to,
IN int tolen
);
Remarks sendto() is used to write outgoing data on a socket. For message-oriented sockets, care
must be taken not to exceed the maximum packet size of the underlying subnets, which
can be obtained by getting the value of socket option SO_MAX_MSG_SIZE. If the data
is too long to pass atomically through the underlying protocol the error WSAEMSGSIZE
is returned, and no data is transmitted.
The to parameter may be any valid address in the socket's address family, including a
broadcast or any multicast address. To send to a broadcast address, an application must
have setsockopt() SO_BROADCAST enabled, otherwise sendto() will fail with the error
code WSAEACCES. For TCP/IP, an application can send to any multicast address
(without becoming a group member).
If the socket is unbound, unique values are assigned to the local association by the system,
and the socket is marked as bound. An application may use getsockname() to determine
the local socket name in this case.
Note that the successful completion of a sendto() does not indicate that the data was
successfully delivered.
To send a broadcast (on a SOCK_DGRAM only), the address in the to parameter should
be constructed using the special IP address INADDR_BROADCAST (defined in
winsock2.h) together with the intended port number. It is generally inadvisable for a
broadcast datagram to exceed the size at which fragmentation may occur, which implies
that the data portion of the datagram (excluding headers) should not exceed 512 bytes.
If no buffer space is available within the transport system to hold the data to be
transmitted, sendto() will block unless the socket has been placed in a non-blocking I/O
mode. On non-blocking stream-oriented sockets, the number of bytes written may be
between 1 and the requested length, depending on buffer availability on both the local and
foreign hosts. The select(), WSAAsyncSelect() or WSAEventSelect() call may be used
to determine when it is possible to send more data.
Calling sendto() with a len of 0 is legal and in this case sendto() will return 0 as a valid
return value. For message-oriented sockets, a zero-length transport datagram is sent.
Flags may be used to influence the behavior of the function invocation beyond the
options specified for the associated socket. That is, the semantics of this function are
determined by the socket options and the flags parameter. The latter is constructed by or-
ing any of the following values:
Value Meaning
MSG_DONTROUTE
Specifies that the data should not be subject to routing. A WinSock
service provider may choose to ignore this flag.
Return Value If no error occurs, sendto() returns the total number of bytes sent. (Note that this may be
less than the number indicated by len.) Otherwise, a value of SOCKET_ERROR is
returned, and a specific error code may be retrieved by calling WSAGetLastError().
WSAEHOSTUNREACH The remote host can't be reached from this host at this
time.
4.19. setsockopt()
Description Set a socket option.
#include <winsock2.h>
int WSAAPI
setsockopt (
IN SOCKET s,
IN int level,
IN int optname,
IN const char FAR * optval,
IN int optlen
);
level The level at which the option is defined; the supported levels include
SOL_SOCKET and IPPROTO_TCP. (See annex for more protocol-
specific levels.)
optval A pointer to the buffer in which the value for the requested option is
supplied.
Remarks setsockopt() sets the current value for a socket option associated with a socket of any
type, in any state. Although options may exist at multiple protocol levels, they are always
present at the uppermost "socket'' level. Options affect socket operations, such as whether
expedited data is received in the normal data stream, whether broadcast messages may be
sent on the socket, etc.
There are two types of socket options: Boolean options that enable or disable a feature or
behavior, and options which require an integer value or structure. To enable a Boolean
option, optval points to a nonzero integer. To disable the option optval points to an
integer equal to zero. optlen should be equal to sizeof(int) for Boolean options. For other
options, optval points to the an integer or structure that contains the desired value for the
option, and optlen is the length of the integer or structure.
The following options are supported for setsockopt(). For default values of these options, see the
description of getsockopt(). The Type identifies the type of data addressed by optval.
Level = SOL_SOCKET
Value Type Meaning
SO_BROADCAST BOOL Allow transmission of broadcast messages on
the socket.
SO_DEBUG BOOL Record debugging information.
SO_DONTLINGER BOOL Don't block close waiting for unsent data to be
sent. Setting this option is equivalent to setting
SO_LINGER with l_onoff set to zero.
SO_DONTROUTE BOOL Don't route: send directly to interface.
setsockopt 79
*
Level = IPPROTO_TCP
SO_DEBUG
WinSock service providers are encouraged (but not required) to supply output debug
information if the SO_DEBUG option is set by an application. The mechanism for
generating the debug information and the form it takes are beyond the scope of this
specification.
SO_GROUP_PRIORITY
Reserved for future use with socket groups: Group priority indicates the relative priority
of the specified socket relative to other sockets within the socket group. Values are non-
negative integers, with zero corresponding to the highest priority. Priority values
represent a hint to the underlying service provider about how potentially scarce resources
should be allocated. For example, whenever two or more sockets are both ready to
80 setsockopt
transmit data, the highest priority socket (lowest value for SO_GROUP_PRIORITY)
should be serviced first, with the remainder serviced in turn according to their relative
priorities.
The WSAENOPROTOOPT error is indicated for non group sockets or for service
providers which do not support group sockets.
SO_KEEPALIVE
An application may request that a TCP/IP provider enable the use of "keep-alive" packets
on TCP connections by turning on the SO_KEEPALIVE socket option. A WinSock
provider need not support the use of keep-alives: if it does, the precise semantics are
implementation-specific but should conform to section 4.2.3.6 of RFC 1122:
Requirements for Internet Hosts -- Communication Layers. If a connection is dropped as
the result of "keep-alives" the error code WSAENETRESET is returned to any calls in
progress on the socket, and any subsequent calls will fail with WSAENOTCONN.
SO_LINGER
SO_LINGER controls the action taken when unsent data is queued on a socket and a
closesocket() is performed. See closesocket() for a description of the way in which the
SO_LINGER settings affect the semantics of closesocket(). The application sets the
desired behavior by creating a struct linger (pointed to by the optval argument) with the
following elements:
struct linger {
u_short l_onoff;
u_short l_linger;
}
To enable SO_LINGER, the application should set l_onoff to a non-zero value, set
l_linger to 0 or the desired timeout (in seconds), and call setsockopt(). To enable
SO_DONTLINGER (i.e. disable SO_LINGER) l_onoff should be set to zero and
setsockopt() should be called. Note that enabling SO_LINGER with a non-zero timeout
on a non-blocking socket is not recommended (see section 4.3. for details).
Enabling SO_LINGER also disables SO_DONTLINGER, and vice versa. Note that if
SO_DONTLINGER is DISABLED (i.e. SO_LINGER is ENABLED) then no timeout
value is specified. In this case the timeout used is implementation dependent. If a previous
timeout has been established for a socket (by enabling SO_LINGER), then this timeout
value should be reinstated by the service provider.
SO_REUSEADDR
By default, a socket may not be bound (see bind()) to a local address which is already in
use. On occasions, however, it may be desirable to "re-use" an address in this way. Since
every connection is uniquely identified by the combination of local and remote addresses,
there is no problem with having two sockets bound to the same local address as long as
the remote addresses are different. To inform the WinSock provider that a bind() on a
socket should not be disallowed because the desired address is already in use by another
socket, the application should set the SO_REUSEADDR socket option for the socket
before issuing the bind(). Note that the option is interpreted only at the time of the
bind(): it is therefore unnecessary (but harmless) to set the option on a socket which is not
to be bound to an existing address, and setting or resetting the option after the bind() has
no effect on this or any other socket.
SO_RCVBUF
SO_SNDBUF
setsockopt 81
PVD_CONFIG
This object stores the configuration information for the service provider associated with
socket s. The exact format of this data structure is service provider specific.
TCP_NODELAY
The TCP_NODELAY option is specific to TCP/IP service providers. Enabling the
TCP_NODELAY option disables the TCP Nagle Algorithm (and vice versa). The Nagle
algorithm (described in RFC 896) is very effective in reducing the number of small
packets sent by a host by essentially buffering send data if there is unacknowledged data
already “in flight” or until a full-size packet can be sent. It is highly recommended that
TCP/IP service providers enable the Nagle Algorithm by default, and for the vast majority
of application protocols the Nagle Algorithm can deliver significant performance
enhancements. However, for some applications this algorithm can impede performance,
and TCP_NODELAY may be used to turn it off. These are applications where many
small messages are sent, which need to be received by the peer with the time delays
between the messages maintained. Application writers should not set TCP_NODELAY
unless the impact of doing so is well-understood and desired, since setting
TCP_NODELAY can have a significant negative impact of network and application
performance.
4.20. shutdown()
Description Disable sends and/or receives on a socket.
#include <winsock2.h>
int WSAAPI
shutdown (
IN SOCKET s,
IN int how
);
how A flag that describes what types of operation will no longer be allowed.
Remarks shutdown() is used on all types of sockets to disable reception, transmission, or both.
If how is SD_RECEIVE, subsequent receives on the socket will be disallowed. This has
no effect on the lower protocol layers. For TCP sockets, if there is still data queued on
the socket waiting to be received, or data arrives subsequently, the connection is reset,
since the data cannot be delivered to the user. For UDP sockets, incoming datagrams are
accepted and queued. In no case will an ICMP error packet be generated.
If how is SD_SEND, subsequent sends are disallowed. For TCP sockets, a FIN will be
sent after all data is sent and acknowledged by the receiver..
Setting how to SD_BOTH disables both sends and receives as described above.
Note that shutdown() does not close the socket, and resources attached to the socket will
not be freed until closesocket() is invoked.
To assure that all data is sent and received on a connected socket before it is closed, an
application should use shutdown() to close connection before calling closesocket(). For
example, to initiate a graceful disconnect, an application could:
Comments shutdown() does not block regardless of the SO_LINGER setting on the socket.
An application should not rely on being able to re-use a socket after it has been shut
down. In particular, a WinSock provider is not required to support the use of connect()
on such a socket.
4.21. socket()
Description Create a socket which is bound to a specific service provider.
#include <winsock2.h>
SOCKET WSAAPI
socket (
IN int af,
IN int type,
IN int protocol
);
protocol A particular protocol to be used with the socket which is specific to the
indicated address family.
Remarks socket() causes a socket descriptor and any related resources to be allocated and bound to
a specific transport service provider. WinSock will utilize the first available service
provider that supports the requested combination of address family, socket type and
protocol parameters. The socket created will have the overlapped attribute by default.
Note that on Microsoft operating systems there is a Microsoft-specific socket option,
SO_OPENTYPE, defined in “mswsock.h” that can affect this default. See Microsoft-
specific documentation for a detailed description of SO_OPENTYPE. Sockets without
the overlapped attribute can be created by using WSASocket(). All functions that allow
overlapped operation (WSASend(), WSARecv(),WSASendTo(), WSARecvFrom(),
WSAIoctl()) also support non-overlapped usage on an overlapped socket if the values for
parameters related to overlapped operation are NULL.
When selecting a protocol and its supporting service provider this procedure will only
choose a base protocol or a protocol chain, not a protocol layer by itself. Unchained
protocol layers are not considered to have "partial matches" on type or af either. That is,
they do not lead to an error code of WSAEAFNOSUPPORT or
WSAEPROTONOSUPPORT if no suitable protocol is found.
Note: the manifest constant AF_UNSPEC continues to be defined in the header file but
its use is strongly discouraged, as this may cause ambiguity in interpreting the value of
the protocol parameter.
The following are the only two type specifications supported for WinSock 1.1:
Type Explanation
SOCK_STREAM Provides sequenced, reliable, two-way, connection-
based byte streams with an out-of-band data
transmission mechanism. Uses TCP for the Internet
address family.
In WinSock 2 many new socket types will be introduced. However, since an application
can dynamically discover the attributes of each available transport protocol via the
WSAEnumProtocols() function, the various socket types need not be called out in the
API specification. Socket type definitions will appear in Winsock2.h which will be
periodically updated as new socket types, address families and protocols are defined.
Support for sockets with type RAW is not required but service providers are encouraged
to support raw sockets whenever it makes sense to do so.
Return Value If no error occurs, socket() returns a descriptor referencing the new socket. Otherwise, a
value of INVALID_SOCKET is returned, and a specific error code may be retrieved by
calling WSAGetLastError().
See Also accept(), bind(), connect(), getsockname(), getsockopt(), setsockopt(), listen(), recv(),
recvfrom(), select(), send(), sendto(), shutdown(), ioctlsocket(), WSASocket().
88 WSAAccept
4.22. WSAAccept()
Description Conditionally accept a connection based on the return value of a condition function,
optionally create and/or join a socket group, provide QOS flowspecs, and allow transfer
of connection data.
#include <winsock2.h>
SOCKET WSAAPI
WSAAccept (
IN SOCKET s,
OUT struct sockaddr FAR * addr,
IN OUT LPINT addrlen,
IN LPCONDITIONPROC lpfnCondition,
IN DWORD dwCallbackData
);
dwCallbackData The callback data passed back to the application as the value of the
dwCallbackData parameter of the condition function. This parameter
is not interpreted by WinSock.
Remarks This routine extracts the first connection on the queue of pending connections on s, and
checks it against the condition function, provided the condition function is specified (i.e.,
not NULL). If the condition function returns CF_ACCEPT, this routine creates a new
socket and performs any socket grouping as indicated by the result parameter g in the
condition function . The newly created socket has the same properties as s including
asynchronous events registered with WSAAsyncSelect() or with WSAEventSelect(), but
not including the listening socket’s group ID, if any. If the condition function returns
CF_REJECT, this routine rejects the connection request. The condition function runs in
the same thread as this routine does, and should return as soon as possible. If the decision
cannot be made immediately, the condition function should return CF_DEFER to indicate
that no decision has been made, and no action about this connection request should be
taken by the service provider. When the application is ready to take action on the
connection request, it will invoke WSAAccept() again and return either CF_ACCEPT or
CF_REJECT as a return value from the condition function.
WSAAccept 89
For sockets which remain in the (default) blocking mode, if no pending connections are
present on the queue, WSAAccept() blocks the caller until a connection is present. For
sockets in a non-blocking mode, if this function is called when no pending connections
are present on the queue, WSAAccept() fails with the error WSAEWOULDBLOCK, as
described below.
After WSAAccept() succeeds, and returns a new socket handle, that accepted socket may
not be used to accept more connections. The original socket remains open, and listening
for new connection requests..
The argument addr is a result parameter that is filled in with the address of the connecting
entity, as known to the communications layer. The exact format of the addr parameter is
determined by the address family in which the communication is occurring. The addrlen
is a value-result parameter; it should initially contain the amount of space pointed to by
addr. On return, it will contain the actual length (in bytes) of the address returned. This
call is used with connection-oriented socket types such as SOCK_STREAM. If addr
and/or addrlen are equal to NULL, then no information about the remote address of the
accepted socket is returned. Otherwise, these two parameters will be filled in regardless
of whether the condition function is specified or what it returns.
int CALLBACK
ConditionFunc(
IN LPWSABUF lpCallerId,
IN LPWSABUF lpCallerData,
IN OUT LPQOS lpSQOS,
IN OUT LPQOS lpGQOS,
IN LPWSABUF lpCalleeId,
OUT LPWSABUF lpCalleeData,
OUT GROUP FAR * g,
IN DWORD dwCallbackData
);
The lpCallerId and lpCallerData are value parameters which contain the address of the
connecting entity and any user data that was sent along with the connection request,
respectively. If no caller ID or caller data is available, the corresponding parameters will
be NULL. (Many network protocols do not support connect-time caller data. Most
conventional network protocols can be expected to support caller ID information at
connection-request time.) The “buf” part of the WSABUF pointed to by lpCallerId points
to a SOCKADDR. The SOCKADDR is interpreted according to its address family
(typically by casting the SOCKADDR to some type specific to the address family).
lpSQOS references the flow specs for socket s specified by the caller, one for each
direction, followed by any additional provider-specific parameters. The sending or
receiving flow spec values will be ignored as appropriate for any unidirectional sockets. A
NULL value for lpSQOS indicates that there is no caller supplied QOS and that no
negotiation is possible. A non-NULL lpSQOS pointer indicates that a QOS negotiation is
to occur or that the provider is prepared to accept the QOS request without negotiation.
90 WSAAccept
Reserved for future use with socket groups: lpGQOS references the flow specs for the
socket group the caller is to create, one for each direction, followed by any additional
provider-specific parameters. A NULL value for lpGQOS indicates no caller-supplied
group QOS. QOS information may be returned if a QOS negotiation is to occur.
The lpCalleeId is a value parameter which contains the local address of the connected
entity. The “buf” part of the WSABUF pointed to by lpCalleeId points to a SOCKADDR.
The SOCKADDR is interpreted according to its address family (typically by casting the
SOCKADDR to some type specific to the address family).
The lpCalleeData is a result parameter used by the condition function to supply user data
back to the connecting entity. lpCalleeData->len initially contains the length of the
buffer allocated by the service provider and pointed to by lpCalleeData->buf. A value of
zero means passing user data back to the caller is not supported. The condition function
should copy up to lpCalleeData->len bytes of data into lpCalleeData->buf , and then
update lpCalleeData->len to indicate the actual number of bytes transferred. If no user
data is to be passed back to the caller, the condition function should set lpCalleeData-
>len to zero. The format of all address and user data is specific to the address family to
which the socket belongs.
Reserved for future use with socket groups: The result parameter g is assigned within the
condition function to indicate the following actions:
if &g is an existing socket group ID, add s to this group, provided all the
requirements set by this group are met; or
if &g = SG_UNCONSTRAINED_GROUP, create an unconstrained socket
group and have s as the first member; or
if &g = SG_CONSTRAINED_GROUP, create a constrained socket group and
have s as the first member; or
if &g = zero, no group operation is performed.
For unconstrained groups, any set of sockets may be grouped together as long as they are
supported by a single service provider. A constrained socket group may consist only of
connection-oriented sockets, and requires that connections on all grouped sockets be to
the same address on the same host. For newly created socket groups, the new group ID
can be retrieved by using getsockopt() with option SO_GROUP_ID, if this operation
completes successfully. A socket group and its associated ID remain valid until the last
socket belonging to this socket group is closed. Socket group IDs are unique across all
processes for a given service provider.
The dwCallbackData parameter value passed to the condition function is the value passed
as the dwCallbackData parameter in the original WSAAccept() call. This value is
interpreted only by the WinSock 2 client. This allows a client to pass some context
information from the WSAAccept() call site through to the condition function. This
gives the condition function any additional information required to determine whether to
accept the connection or not. A typical usage is to pass a (suitably cast) pointer to a data
structure containing references to application-defined objects with which this socket is
associated.
Return Value If no error occurs, WSAAccept() returns a value of type SOCKET which is a descriptor
for the accepted socket. Otherwise, a value of INVALID_SOCKET is returned, and a
specific error code may be retrieved by calling WSAGetLastError().
The integer referred to by addrlen initially contains the amount of space pointed to by
addr. On return it will contain the actual length in bytes of the address returned.
WSAAccept 91
WSAEACCES The connection request that was offered has timed out
or been withdrawn.
4.23. WSAAsyncSelect()
Description Request Windows message-based notification of network events for a socket.
int WSAAPI
WSAAsyncSelect (
IN SOCKET s,
IN HWND hWnd,
IN unsigned int wMsg,
IN long lEvent
);
hWnd A handle identifying the window which should receive a message when
a network event occurs.
Remarks This function is used to request that the WinSock DLL should send a message to the
window hWnd whenever it detects any of the network events specified by the lEvent
parameter. The message which should be sent is specified by the wMsg parameter. The
socket for which notification is required is identified by s.
This function automatically sets socket s to non-blocking mode, regardless of the value of
lEvent. See ioctlsocket() about how to set the non-blocking socket back to blocking
mode.
The lEvent parameter is constructed by or'ing any of the values specified in the following
list.
Value Meaning
FD_READ Want to receive notification of readiness for reading
FD_WRITE Want to receive notification of readiness for writing
FD_OOB Want to receive notification of the arrival of out-of-band
data
FD_ACCEPT Want to receive notification of incoming connections
FD_CONNECT Want to receive notification of completed connection or
multipoint “join” operation
FD_CLOSE Want to receive notification of socket closure
FD_QOS Want to receive notification of socket Quality of Service
(QOS) changes
FD_GROUP_QOS Reserved for future use with socket groups: Want to
receive notification of socket group Quality of Service
(QOS) changes
FD_ROUTING_INTERFACE_CHANGE
Want to receive notification of routing interface changes
for the specified destination(s)
WSAAsyncSelect 93
FD_ADDRESS_LIST_CHANGE
Want to receive notification of local address list changes
for the socket’s protocol family
It is not possible to specify different messages for different events. The following code
will not work; the second call will cancel the effects of the first, and only FD_WRITE
events will be reported with message wMsg2:
To cancel all notification − i.e., to indicate that WinSock should send no further messages
related to network events on the socket − lEvent should be set to zero.
Since an accept()'ed socket has the same properties as the listening socket used to accept
it, any WSAAsyncSelect() events set for the listening socket apply to the accepted socket.
For example, if a listening socket has WSAAsyncSelect() events FD_ACCEPT,
FD_READ, and FD_WRITE, then any socket accepted on that listening socket will also
have FD_ACCEPT, FD_READ, and FD_WRITE events with the same wMsg value used
for messages. If a different wMsg or events are desired, the application should call
WSAAsyncSelect(), passing the accepted socket and the desired new information.2
When one of the nominated network events occurs on the specified socket s, the
application's window hWnd receives message wMsg. The wParam argument identifies
the socket on which a network event has occurred. The low word of lParam specifies the
network event that has occurred. The high word of lParam contains any error code. The
error code be any error as defined in winsock2.h. Note: Upon receipt of an event
notification message the WSAGetLastError() function cannot be used to check the error
value, because the error value returned may differ from the value in the high word of
lParam.
2
Note that there is a timing window between the accept() call and the call to WSAAsyncSelect() to change
the events or wMsg. An application which desires a different wMsg for the listening and accept()'ed
sockets should ask for only FD_ACCEPT events on the listening socket, then set appropriate events after
the accept(). Since FD_ACCEPT is never sent for a connected socket and FD_READ, FD_WRITE,
FD_OOB, and FD_CLOSE are never sent for listening sockets, this will not impose difficulties.
94 WSAAsyncSelect
The error and event codes may be extracted from the lParam using the macros
WSAGETSELECTERROR and WSAGETSELECTEVENT, defined in winsock2.h as:
The use of these macros will maximize the portability of the source code for the
application.
The possible network event codes which may be returned are as follows:
Value Meaning
FD_READ Socket s ready for reading
FD_WRITE Socket s ready for writing
FD_OOB Out-of-band data ready for reading on socket s
FD_ACCEPT Socket s ready for accepting a new incoming connection
FD_CONNECT Connection or multipoint “join” operation initiated on
socket s completed
FD_CLOSE Connection identified by socket s has been closed
FD_QOS Quality of Service associated with socket s has changed
FD_GROUP_QOS Reserved for future use with socket groups: Quality of
Service associated with the socket group to which s belongs
has changed
FD_ROUTING_INTERFACE_CHANGE
Local interface that should be used to send to the specified
destination has changed
FD_ADDRESS_LIST_CHANGE
The list of addresses of the socket’s protocol family to
which the application client can bind has changed
Return Value The return value is 0 if the application's declaration of interest in the network event set
was successful. Otherwise the value SOCKET_ERROR is returned, and a specific error
number may be retrieved by calling WSAGetLastError().
Comments Although WSAAsyncSelect() can be called with interest in multiple events, the
application window will receive a single message for each network event.
The Winsock DLL will not continually flood an application with messages for a particular
network event. Having successfully posted notification of a particular event to an
application window, no further message(s) for that network event will be posted to the
application window until the application makes the function call which implicitly
reenables notification of that network event.
Any call to the reenabling routine, even one which fails, results in reenabling of message
posting for the relevant event.
(i) network transport stack receives 100 bytes of data on socket s and
causes Winsock 2 to post an FD_READ message.
(ii) The application issues recv( s, buffptr, 50, 0) to read 50 bytes.
(iii) another FD_READ message is posted since there is still data to be read.
With these semantics, an application need not read all available data in response to an
FD_READ message--a single recv() in response to each FD_READ message is
appropriate. If an application issues multiple recv() calls in response to a single
FD_READ, it may receive multiple FD_READ messages. Such an application may wish
to disable FD_READ messages before starting the recv() calls by calling
WSAAsyncSelect() with the FD_READ event not set.
The FD_QOS and FD_GROUP_QOS events are considered “edge triggered.” A message
will be posted exactly once when a QOS change occurs. Further messages will not be
forthcoming until either the provider detects a further change in QOS or the application
renegotiates the QOS for the socket.
If any event has already happened when the application calls WSAAsyncSelect() or when
the reenabling function is called, then a message is posted as appropriate. For example,
consider the following sequence: 1) an application calls listen(), 2) a connect request is
received but not yet accepted, 3) the application calls WSAAsyncSelect() specifying that
it wants to receive FD_ACCEPT messages for the socket. Due to the persistence of
events, Winsock 2 posts an FD_ACCEPT message immediately.
The FD_OOB event is used only when a socket is configured to receive out-of-band data
separately (see section 3.5. Out-Of-Band data for a discussion of this topic). If the
socket is configured to receive out-of-band data in-line, the out-of-band (expedited) data
is treated as normal data and the application should register an interest in, and will
receive, FD_READ events, not FD_OOB events. An application may set or inspect the
way in which out-of-band data is to be handled by using setsockopt() or getsockopt() for
the SO_OOBINLINE option.
The error code in an FD_CLOSE message indicates whether the socket close was graceful
or abortive. If the error code is 0, then the close was graceful; if the error code is
WSAECONNRESET, then the socket's virtual circuit was reset. This only applies to
connection-oriented sockets such as SOCK_STREAM.
The FD_CLOSE message is posted when a close indication is received for the virtual
circuit corresponding to the socket. In TCP terms, this means that the FD_CLOSE is
posted when the connection goes into the TIME WAIT or CLOSE WAIT states. This
results from the remote end performing a shutdown() on the send side or a closesocket().
FD_CLOSE should only be posted after all data is read from a socket, but an application
should check for remaining data upon receipt of FD_CLOSE to avoid any possibility of
losing data.
Please note your application will receive ONLY an FD_CLOSE message to indicate
closure of a virtual circuit, and only when all the received data has been read if this is a
graceful close. It will NOT receive an FD_READ message to indicate this condition.
The FD_QOS or FD_GROUP_QOS message is posted when any field in the flow spec
associated with socket s or the socket group that s belongs to has changed, respectively.
Applications should use WSAIoctl() with command SIO_GET_QOS or
SIO_GET_GROUP_QOS to get the current QOS for socket s or for the socket group s
belongs to, respectively.
when a change occurs after the application has request the notification by issuing
WSAIoctl() with SIO_ROUTING_INTERFACE_CHANGE or
SIO_ADDRESS_LIST_CHANGE correspondingly. Further messages will not be
forthcoming until the application reissues the IOCTL AND another change is detected
since the IOCTL has been issued.
Here is a summary of events and conditions for each asynchronous notification message:
• FD_READ:
1) when WSAAsyncSelect() called, if there is data currently available to receive,
2) when data arrives, if FD_READ not already posted,
3) after recv() or recvfrom() called (with or without MSG_PEEK), if data is still
available to receive.
(Note: when setsockopt() SO_OOBINLINE is enabled "data" includes both normal
data and out-of-band (OOB) data in the instances noted above.
• FD_WRITE:
1) when WSAAsyncSelect() called, if a send() or sendto() is possible
2) after connect() or accept() called, when connection established
3) after send() or sendto() fail with WSAEWOULDBLOCK, when send() or
sendto() are likely to succeed,
4) after bind() on a connectionless socket. FD_WRITE may or may not occur at this
time (implementation dependent). In any case, a connectionless socket is always
writeable immediately after bind().
• FD_ACCEPT:
1) when WSAAsyncSelect() called, if there is currently a connection request
available to accept,
2) when a connection request arrives, if FD_ACCEPT not already posted,
3) after accept() called, if there is another connection request available to accept.
• FD_CONNECT:
1) when WSAAsyncSelect() called, if there is currently a connection established,
2) after connect() called, when connection is established (even when connect()
succeeds immediately, as is typical with a datagram socket, and even when it
fails immediately).
3) after WSAJoinLeaf() called, when join operation completes.
4) after connect(), WSAConnect(), or WSAJoinLeaf() was called with a non-
blocking, connection-oriented socket. The initial operation returned with a
specific error of WSAEWOULDBLOCK, but the network operation went ahead.
Whether the operation eventually succeeds or not, when the outcome has been
determined, FD_CONNECT happens. The client should check the error code to
determine whether the outcome was success or failure.
2) after remote system initiated graceful close, when no data currently available to
receive (note: if data has been received and is waiting to be read when the remote
system initiates a graceful close, the FD_CLOSE is not delivered until all pending
data has been read),
3) after local system initiates graceful close with shutdown() and remote system has
responded with "End of Data" notification (e.g. TCP FIN), when no data currently
available to receive,
4) when remote system aborts connection (e.g. sent TCP RST), and lParam will
contain WSAECONNRESET error value.
Note: FD_CLOSE is not posted after closesocket() is called.
• FD_QOS:
1) when WSAAsyncSelect() called, if the QOS associated with the socket has been
changed,
2) after WSAIoctl() with SIO_GET_QOS called, when the QOS is changed.
• FD_GROUP_QOS:
Reserved for future use with socket groups:
1) when WSAAsyncSelect() called, if the group QOS associated with the socket has
been changed,
2) after WSAIoctl() with SIO_GET_GROUP_QOS called, when the group QOS is
changed.
• FD_ROUTING_INTERFACE_CHANGE:
1) after WSAIoctl() with SIO_ROUTING_INTERFACE_CHANGE called, when
the local interface that should be used to reach the destination specified in the IOCTL
changes.
• FD_ADDRESS_LIST_CHANGE:
1) after WSAIoctl() with SIO_ADDRESS_LIST_CHANGE called, when the list of
local addresses to which the application can bind changes.
Additional error codes may be set when an application window receives a message. This
error code is extracted from the lParam in the reply message using the
WSAGETSELECTERROR macro. Possible error codes for each network event are:
Event: FD_CONNECT
Error Code Meaning
WSAAsyncSelect 99
Event: FD_CLOSE
Error Code Meaning
WSAENETDOWN The network subsystem has failed.
Event: FD_READ
Event: FD_WRITE
Event: FD_OOB
Event: FD_ACCEPT
Event: FD_QOS
Event: FD_GROUP_QOS
Event: FD_ADDRESS_LIST_CHANGE
Error Code Meaning
WSAENETDOWN The network subsystem has failed.
Event: FD_ROUTING_INTERFACE_CHANGE
Error Code Meaning
WSAENETUNREACH The specified destination is no longer reachable
WSAENETDOWN The network subsystem has failed.
4.24. WSACancelBlockingCall()
Description Cancel a blocking call which is currently in progress. WSACancelBlockingCall() is only
available for WinSock 1.1 apps (that is, if at least one thread within the process negotiates
version 1.0 or 1.1 at WSAStartup()).
Important Note: This function is for backwards compatibility with WinSock 1.1 and is
not considered part of the WinSock 2 specification. WinSock 2 applications should not
use this function.
#include <winsock2.h>
Remarks This function cancels any outstanding blocking operation for this thread. It is normally
used in two situations:
(1) An application is processing a message which has been received while a blocking call
is in progress. In this case, WSAIsBlocking() will be true.
(2) A blocking call is in progress, and WinSock has called back to the application's
"blocking hook" function (as established by WSASetBlockingHook()).
In each case, the original blocking call will terminate as soon as possible with the error
WSAEINTR. (In (1), the termination will not take place until Windows message
scheduling has caused control to revert to the blocking routine in WinSock. In (2), the
blocking call will be terminated as soon as the blocking hook function completes.)
In the case of a blocking connect()operation, WinSock will terminate the blocking call as
soon as possible, but it may not be possible for the socket resources to be released until
the connection has completed (and then been reset) or timed out. This is likely to be
noticeable only if the application immediately tries to open a new socket (if no sockets are
available), or to connect() to the same peer.
Canceling an accept() or a select() call does not adversely impact the sockets passed to
these calls. Only the particular call fails; any operation that was legal before the cancel is
legal after the cancel, and the state of the socket is not affected in any way.
Canceling any operation other than accept() and select() can leave the socket in an
indeterminate state. If an application cancels a blocking operation on a socket, the only
operation that the application can depend on being able to perform on the socket is a call
to closesocket(), although other operations may work on some WinSock implementations.
If an application desires maximum portability, it must be careful not to depend on
performing operations after a cancel. An application may reset the connection by setting
the timeout on SO_LINGER to 0 and calling closesocket().
Return Value The value returned by WSACancelBlockingCall() is 0 if the operation was successfully
canceled. Otherwise the value SOCKET_ERROR is returned, and a specific error
number may be retrieved by calling WSAGetLastError().
WSACancelBlockingCall 101
Comments Note that it is possible that the network operation completes before the
WSACancelBlockingCall() is processed, for example if data is received into the user
buffer at interrupt time while the application is in a blocking hook. In this case, the
blocking operation will return successfully as if WSACancelBlockingCall() had never
been called. Note that the WSACancelBlockingCall() still succeeds in this case; the
only way to know with certainty that an operation was actually canceled is to check for a
return code of WSAEINTR from the blocking call.
4.25. WSACleanup()
Description Terminate use of the WinSock DLL.
#include <winsock2.h>
There must be a call to WSACleanup() for every successful call to WSAStartup() made
by a task. Only the final WSACleanup() for that task does the actual cleanup; the
preceding calls simply decrement an internal reference count in the WinSock DLL.
Return Value The return value is 0 if the operation was successful. Otherwise the value
SOCKET_ERROR is returned, and a specific error number may be retrieved by calling
WSAGetLastError().
Comments Attempting to call WSACleanup() from within a blocking hook and then failing to check
the return code is a common programming error in WinSock 1.1 applications. If an
application needs to quit while a blocking call is outstanding, the application must first
cancel the blocking call with WSACancelBlockingCall() then issue the WSACleanup()
call once control has been returned to the application.
4.26. WSACloseEvent()
Description Closes an open event object handle.
#include <winsock2.h>
BOOL WSAAPI
WSACloseEvent(
IN WSAEVENT hEvent
);
Remarks The handle to the event object is closed so that further references to this handle will fail
with the error WSA_INVALID_HANDLE.
If the function fails, the return value is FALSE. To get extended error information, call
WSAGetLastError().
4.27. WSAConnect()
Description Establish a connection to a peer, exchange connect data, and specify needed quality of
service based on the supplied flow spec.
#include <winsock2.h>
int WSAAPI
WSAConnect (
IN SOCKET s,
IN const struct sockaddr FAR * name,
IN int namelen,
IN LPWSABUF lpCallerData,
OUT LPWSABUF lpCalleeData,
IN LPQOS lpSQOS,
IN LPQOS lpGQOS
);
lpCallerData A pointer to the user data that is to be transferred to the peer during
connection establishment.
lpCalleeData A pointer to the user data that is to be transferred back from the peer
during connection establishment.
lpSQOS A pointer to the flow specs for socket s, one for each direction.
lpGQOS Reserved for future use with socket groups: A pointer to the flow specs
for the socket group (if applicable).
Remarks This function is used to create a connection to the specified destination, and to perform a
number of other ancillary operations that occur at connect time as well. If the socket, s, is
unbound, unique values are assigned to the local association by the system, and the socket
is marked as bound.
FD_CONNECT and the error code associated with the FD_CONNECT indicates either
success or a specific reason for failure.
For connectionless sockets, name may indicate any valid address, including a broadcast
address. However, to connect to a broadcast address, a socket must have setsockopt()
SO_BROADCAST enabled, otherwise WSAConnect() will fail with the error code
WSAEACCES.
On connectionless sockets, exchange of user to user data is not possible and the
corresponding parameters will be silently ignored.
The application is responsible for allocating any memory space pointed to directly or
indirectly by any of the parameters it specifies.
The lpCallerData is a value parameter which contains any user data that is to be sent
along with the connection request. If lpCallerData is NULL, no user data will be passed
to the peer. The lpCalleeData is a result parameter which will contain any user data
passed back from the peer as part of the connection establishment. lpCalleeData->len
initially contains the length of the buffer allocated by the application and pointed to by
lpCalleeData->buf. lpCalleeData->len will be set to 0 if no user data has been passed
back. The lpCalleeData information will be valid when the connection operation is
complete. For blocking sockets, this will be when the WSAConnect() function returns.
For non-blocking sockets, this will be after the FD_CONNECT notification has occurred.
If lpCalleeData is NULL, no user data will be passed back. The exact format of the user
data is specific to the address family to which the socket belongs.
At connect time, an application may use the lpSQOS and/or lpGQOS parameters to
override any previous QOS specification made for the socket via WSAIoctl() with either
the SIO_SET_QOS or SIO_SET_GROUP_QOS opcodes.
lpSQOS specifies the flow specs for socket s, one for each direction, followed by any
additional provider-specific parameters. If either the associated transport provider in
general or the specific type of socket in particular cannot honor the QOS request, an error
will be returned as indicated below. The sending or receiving flow spec values will be
ignored, respectively, for any unidirectional sockets. If no provider-specific parameters
are supplied, the buf and len fields of lpSQOS->ProviderSpecific should be set to NULL
and 0, respectively. A NULL value for lpSQOS indicates no application supplied QOS.
Reserved for future use with socket groups: lpGQOS specifies the flow specs for the
socket group (if applicable), one for each direction, followed by any additional provider-
specific parameters. If no provider-specific parameters are supplied, the buf and len
106 WSAConnect
Comments When connected sockets break (i.e. become closed for whatever reason), they should be
discarded and recreated. It is safest to assume that when things go awry for any reason
on a connected socket, the application must discard and recreate the needed sockets in
order to return to a stable point.
On a blocking socket, the return value indicates success or failure of the connection
attempt.
With a non-blocking socket, the connection attempt may not be completed immediately -
in this case WSAConnect() will return SOCKET_ERROR, and WSAGetLastError()
will return WSAEWOULDBLOCK. In this case the application may:
1. Use select() to determine the completion of the connection request by checking if the
socket is writeable, or
For a non-blocking socket, until the connection attempt completes all subsequent calls to
WSAConnect() on the same socket will fail with the error code WSAEALREADY, and
WSAEISCONN when the connection completes successfully. Due to ambiguities in
version 1.1 of the Windows Sockets specification, error codes returned from connect()
while a connection is already pending may vary among implementations. As a result, it
isn’t recommended that applications use multiple calls to connect() to detect connection
completion. If they do, they must be prepared to handle WSAEINVAL and
WSAEWOULDBLOCK error values the same way that they handle WSAEALREADY,
to assure robust execution.
If the return error code indicates the connection attempt failed (i.e.
WSAECONNREFUSED, WSAENETUNREACH, WSAETIMEDOUT) the application
may call WSAConnect() again for the same socket.
4.28. WSACreateEvent()
Description Creates a new event object.
#include <winsock2.h>
Remarks The event object created by this function is manual reset, with an initial state of
nonsignaled. WinSock 2 event objects are system objects in Win32 environments.
Therefore, if a Win32 application desires auto reset events, it may call the native
CreateEvent() Win32 API directly. The scope of an event object is limited to the process
in which it is created.
Return Value If the function succeeds, the return value is the handle of the event object.
If the function fails, the return value is WSA_INVALID_EVENT. To get extended error
information, call WSAGetLastError().
4.29. WSADuplicateSocket()
Description Return a WSAPROTOCOL_INFO structure that can be used to create a new socket
descriptor for a shared socket.
#include <winsock2.h>
int WSAAPI
WSADuplicateSocket (
IN SOCKET s,
IN DWORD dwProcessId,
OUT LPWSAPROTOCOL_INFO lpProtocolInfo
);
dwProcessId Specifies the ID of the target process for which the shared socket will
be used.
Remarks This function is used to enable socket sharing between processes. A source process calls
WSADuplicateSocket() to obtain a special WSAPROTOCOL_INFO structure. It uses
some interprocess communications (IPC) mechanism to pass the contents of this structure
to a target process, which in turn uses it in a call to WSASocket() to obtain a descriptor
for the duplicated socket. Note that the special WSAPROTOCOL_INFO structure may
only be used once by the target process.
Note that sockets may be shared amongst threads in a given process without using the
WSADuplicateSocket() function, since a socket descriptor is valid in all of a process’
threads.
One possible scenario for establishing and using a shared socket in a handoff mode is
illustrated below:
Comments The descriptors that reference a shared socket may be used independently as far as I/O is
concerned. However, the WinSock interface does not implement any type of access
control, so it is up to the processes involved to coordinate their operations on a shared
socket. A typical use for shared sockets is to have one process that is responsible for
creating sockets and establishing connections, hand off sockets to other processes which
are responsible for information exchange.
Since what is duplicated are the socket descriptors and not the underlying socket, all of
the state associated with a socket is held in common across all the descriptors. For
example a setsockopt() operation performed using one descriptor is subsequently visible
using a getsockopt() from any or all descriptors. A process may call closesocket() on a
duplicated socket and the descriptor will become deallocated. The underlying socket,
however, will remain open until closesocket() is called by the last remaining descriptor.
4.30. WSAEnumNetworkEvents()
Description Discover occurrences of network events for the indicated socket, clear internal network
events record, and (optionally) reset event object.
#include <winsock2.h>
int WSAAPI
WSAEnumNetworkEvents (
IN SOCKET s,
IN WSAEVENT hEventObject,
OUT LPWSANETWORKEVENTS lpNetworkEvents
);
Remarks This function is used to discover which network events have occurred for the indicated
socket since the last invocation of this function. It is intended for use in conjunction with
WSAEventSelect(), which associates an event object with one or more network events.
Recording of network events commences when WSAEventSelect() is called with a non-
zero lNetworkEvents parameter and remains in effect until another call is made to
WSAEventSelect() with the lNetworkEvents parameter set to zero, or until a call is made
to WSAAsyncSelect().
The socket’s internal record of network events is copied to the structure referenced by
lpNetworkEvents, whereafter the internal network events record is cleared. If
hEventObject is non-null, the indicated event object is also reset. The WinSock provider
guarantees that the operations of copying the network event record, clearing it and
resetting any associated event object are atomic, such that the next occurrence of a
nominated network event will cause the event object to become set. In the case of this
function returning SOCKET_ERROR, the associated event object is not reset and the
record of network events is not cleared.
The lNetworkEvents field of the structure indicates which of the FD_XXX network events
have occurred. The iErrorCode array is used to contain any associated error codes, with
array index corresponding to the position of event bits in lNetworkEvents. The identifiers
FD_READ_BIT, FD_WRITE_BIT, etc. may be used to index the iErrorCode array.
Note that only those elements of the iErrorCode array are set that correspond to the bits
114 WSAEnumNetworkEvents
set in lNetworkEvents field. Other fields are not modified (this is important for
backwards compatibility with the applications that are not aware of new
FD_ROUTING_INTERFACE_CHANGE and FD_ADDRESS_LIST_CHANGE events).
The following error codes may be returned along with the respective network event:
Event: FD_CONNECT
Error Code Meaning
WSAEAFNOSUPPORT Addresses in the specified family cannot be used with
this socket.
Event: FD_CLOSE
Error Code Meaning
WSAENETDOWN The network subsystem has failed.
Event: FD_READ
Event: FD_WRITE
Event: FD_OOB
Event: FD_ACCEPT
Event: FD_QOS
Event: FD_GROUP_QOS
Event: FD_ADDRESS_LIST_CHANGE
Error Code Meaning
WSAENETDOWN The network subsystem has failed.
Event: FD_ROUTING_INTERFACE_CHANGE
Error Code Meaning
WSAENETUNREACH The specified destination is no longer reachable
WSAENETDOWN The network subsystem has failed.
Return Value The return value is 0 if the operation was successful. Otherwise the value
SOCKET_ERROR is returned, and a specific error number may be retrieved by calling
WSAGetLastError().
4.31. WSAEnumProtocols()
Description Retrieve information about available transport protocols.
#include <winsock2.h>
int WSAAPI
WSAEnumProtocols (
IN LPINT lpiProtocols,
OUT LPWSAPROTOCOL_INFO lpProtocolBuffer,
IN OUT LPDWORD lpdwBufferLength
);
Remarks This function is used to discover information about the collection of transport protocols
and protocol chains installed on the local machine. Since layered protocols are only
usable by applications when installed in protocol chains, information on layered protocols
is not included in lpProtocolBuffer. The lpiProtocols parameter can be used as a filter to
constrain the amount of information provided. Normally it will be supplied as a NULL
pointer which will cause the routine to return information on all available transport
protocols and protocol chains.
The order in which the WSAPROTOCOL_INFO structs appear in the buffer coincides
with the order in which the protocol entries were registered by the service provider with
the WinSock DLL, or with any subsequent re-ordering that may have occurred via the
WinSock applet or DLL supplied for establishing default TCP/IP providers.
DWORD dwProviderFlags - provide information about how this protocol is represented in the
protocol catalog. The following flag values are possible:
PFL_HIDDEN - set by a provider to indicate to the WinSock 2 DLL that this protocol
should not be returned in the result buffer generated by WSAEnumProtocols().
Obviously, a WinSock 2 application should never see an entry with this bit set.
GUID ProviderId- A globally unique identifier assigned to the provider by the service provider
vendor. This value is useful for instances where more than one service provider is able to
implement a particular protocol. An application may use the ProviderId value to distinguish
between providers that might otherwise be indistinguishable.
DWORD dwCatalogEntryId - A unique identifier assigned by the WinSock 2 DLL for each
WSAPROTOCOL_INFO structure.
The corresponding Catalog Entry IDs are in the ProtocolChain.ChainEntries array starting
with the layered protocol at the top (the zeroth element in the ProtocolChain.ChainEntries
array) and ending with the base protocol. Refer to the WinSock 2 Service Provider Interface
specification for more information on protocol chains.
int iAddressFamily - the value to pass as the address family parameter to the socket()/WSASocket()
function in order to open a socket for this protocol. This value also uniquely defines the
structure of protocol addresses (SOCKADDRs) used by the protocol.
int iMaxSockAddr - The maximum address length in bytes (e.g. 16 for IP version 4, the equivalent of
sizeof(SOCKADDR_IN)).
int iMinSockAddr - The minimum address length (same as iMaxSockAddr, unless protocol supports
variable length addressing).
int iSocketType - The value to pass as the socket type parameter to the socket() function in order to
open a socket for this protocol.
int iProtocol - The value to pass as the protocol parameter to the socket() function in order to open a
socket for this protocol.
int iProtocolMaxOffset - The maximum value that may be added to iProtocol when supplying a
value for the protocol parameter to socket() and WSASocket(). Not all protocols allow a
range of values. When this is the case iProtocolMaxOffset will be zero.
int iNetworkByteOrder - Currently these values are manifest constants (BIGENDIAN and
LITTLEENDIAN) that indicate either “big-endian” or “little-endian” with the values 0 and 1
respectively.
int iSecurityScheme - Indicates the type of security scheme employed (if any). A value of
SECURITY_PROTOCOL_NONE is used for protocols that do not incorporate security
provisions.
DWORD dwMessageSize - The maximum message size supported by the protocol. This is the
maximum size that can be sent from any of the host’s local interfaces. For protocols which
do not support message framing, the actual maximum that can be sent to a given address may
be less. There is no standard provision to determine the maximum inbound message size.
The following special values are defined:
0 - the protocol is stream-oriented and hence the concept of message size is not
relevant.
char szProtocol - an array of characters that contains a human-readable name identifying the
protocol, for example "SPX". The maximum number of characters allowed is
WSAPROTOCOL_LEN, which is defined to be 255.
Return Value If no error occurs, WSAEnumProtocols() returns the number of protocols to be reported
on. Otherwise a value of SOCKET_ERROR is returned and a specific error code may be
retrieved by calling WSAGetLastError().
WSAENOBUFS The buffer length was too small to receive all the
relevant WSAPROTOCOL_INFO structures and
associated information. Pass in a buffer at least as
large as the value returned in lpdwBufferLength.
4.32. WSAEventSelect()
Description Specify an event object to be associated with the supplied set of FD_XXX network
events.
#include <winsock2.h>
int WSAAPI
WSAEventSelect (
IN SOCKET s,
IN WSAEVENT hEventObject,
IN long lNetworkEvents
);
hEventObject A handle identifying the event object to be associated with the supplied
set of FD_XXX network events.
Remarks This function is used to specify an event object, hEventObject, to be associated with the
selected FD_XXX network events, lNetworkEvents. The socket for which an event object
is specified is identified by s. The event object is set when any of the nominated network
events occur.
WSAEventSelect() is the only function that causes network activity and errors to be
recorded and retrievable through WSAEnumNetworkEvents(). See the descriptions of
select() and WSAAsyncSelect() to find out how those functions report network activity
and errors.
This function automatically sets socket s to non-blocking mode, regardless of the value of
lNetworkEvents. See ioctlsocket()/WSAIoctl() about how to set the socket back to
blocking mode.
The lNetworkEvents parameter is constructed by or'ing any of the values specified in the
following list.
Value Meaning
FD_READ Want to receive notification of readiness for reading
FD_WRITE Want to receive notification of readiness for writing
FD_OOB Want to receive notification of the arrival of out-of-band
data
122 WSAEventSelect
It is not possible to specify different event objects for different network events. The
following code will not work; the second call will cancel the effects of the first, and only
FD_WRITE network event will be associated with hEventObject2:
Closing a socket with closesocket() also cancels the association and selection of network
events specified in WSAEventSelect() for the socket. The application, however, still
must call WSACloseEvent() to explicitly close the event object and free any resources.
Since an accept()'ed socket has the same properties as the listening socket used to accept
it, any WSAEventSelect() association and network events selection set for the listening
socket apply to the accepted socket. For example, if a listening socket has
WSAEventSelect() association of hEventOject with FD_ACCEPT, FD_READ, and
FD_WRITE, then any socket accepted on that listening socket will also have
FD_ACCEPT, FD_READ, and FD_WRITE network events associated with the same
hEventObject. If a different hEventObject or network events are desired, the application
should call WSAEventSelect(), passing the accepted socket and the desired new
information.3
3
Note that there is a timing window between the accept() call and the call to WSAEventSelect() to change
the network events or hEventObject. An application which desires a different hEventObject for the
listening and accept()'ed sockets should ask for only FD_ACCEPT network event on the listening socket,
then set appropriate network events after the accept(). Since FD_ACCEPT never happens to a connected
WSAEventSelect 123
Return Value The return value is 0 if the application's specification of the network events and the
associated event object was successful. Otherwise the value SOCKET_ERROR is
returned, and a specific error number may be retrieved by calling WSAGetLastError().
Having successfully recorded the occurrence of the network event (by setting the
corresponding bit in the internal network event record) and signaled the associated event
object, no further actions are taken for that network event until the application makes the
function call which implicitly reenables the setting of that network event and signaling of
the associated event object.
socket and FD_READ, FD_WRITE, FD_OOB, and FD_CLOSE never happen to listening sockets, this will
not impose difficulties.
124 WSAEventSelect
Any call to the reenabling routine, even one which fails, results in reenabling of recording
and signaling for the relevant network event and event object, respectively.
For FD_READ, FD_OOB, and FD_ACCEPT network events, network event recording
and event object signaling are "level-triggered." This means that if the reenabling routine
is called and the relevant network condition is still valid after the call, the network event
is recorded and the associated event object is set . This allows an application to be
event-driven and not be concerned with the amount of data that arrives at any one time.
Consider the following sequence:
(i) transport provider receives 100 bytes of data on socket s and causes
WinSock DLL to record the FD_READ network event and set the
associated event object.
(ii) The application issues recv( s, buffptr, 50, 0) to read 50 bytes.
(iii) The transport provider causes WinSock DLL to record the FD_READ
network event and sets the associated event object again since there is
still data to be read.
With these semantics, an application need not read all available data in response to an
FD_READ network event --a single recv() in response to each FD_READ network event
is appropriate.
The FD_QOS and FD_GROUP_QOS events are considered edge triggered. A message
will be posted exactly once when a QOS change occurs. Further messages will not be
forthcoming until either the provider detects a further change in QOS or the application
renegotiates the QOS for the socket.
If a network event has already happened when the application calls WSAEventSelect() or
when the reenabling function is called, then a network event is recorded and the
associated event object is set as appropriate. For example, consider the following
sequence: 1) an application calls listen(), 2) a connect request is received but not yet
accepted, 3) the application calls WSAEventSelect() specifying that it is interested in the
FD_ACCEPT network event for the socket. Due to the persistence of network events,
WinSock records the FD_ACCEPT network event and sets the associated event object
immediately.
The FD_OOB network event is used only when a socket is configured to receive out-of-
band data separately. If the socket is configured to receive out-of-band data in-line, the
out-of-band (expedited) data is treated as normal data and the application should register
an interest in, and will get, FD_READ network event, not FD_OOB network event. An
application may set or inspect the way in which out-of-band data is to be handled by using
setsockopt() or getsockopt() for the SO_OOBINLINE option.
The error code in an FD_CLOSE network event indicates whether the socket close was
graceful or abortive. If the error code is 0, then the close was graceful; if the error code is
WSAECONNRESET, then the socket's virtual circuit was reset. This only applies to
connection-oriented sockets such as SOCK_STREAM.
The FD_CLOSE network event is recorded when a close indication is received for the
virtual circuit corresponding to the socket. In TCP terms, this means that the FD_CLOSE
is recorded when the connection goes into the TIME WAIT or CLOSE WAIT states.
This results from the remote end performing a shutdown() on the send side or a
closesocket(). FD_CLOSE should only be posted after all data is read from a socket, but
an application should check for remaining data upon receipt of FD_CLOSE to avoid any
possibility of losing data.
Please note WinSock will record ONLY an FD_CLOSE network event to indicate
closure of a virtual circuit. It will NOT record an FD_READ network event to indicate
this condition.
The FD_QOS or FD_GROUP_QOS network event is recorded when any field in the
flow spec associated with socket s or the socket group that s belongs to has changed,
respectively. Applications should use WSAIoctl() with command SIO_GET_QOS or
SIO_GET_GROUP_QOS to get the current QOS for socket s or for the socket group s
belongs to, respectively.
4.33. WSAGetLastError()
Description Get the error status for the last operation which failed.
#include <winsock2.h>
Remarks This function returns the last network error that occurred. When a particular WinSock
function indicates that an error has occurred, this function should be called to retrieve the
appropriate error code. This error code may be different from the error code obtained
from getsockopt() SO_ERROR—which is socket-specific--since WSAGetLastError() is
for all sockets (i.e., thread-specific)..
A successful function call, or a call to WSAGetLastError(), does not reset the error
code. To reset the error code, use the WSASetLastError() function call with iError set
to zero (NOTE: getsockopt() SO_ERROR also resets the error code to zero)
This function should not be used to check for an error value on receipt of an
asynchronous message. In this case the error value is passed in the lParam field of the
message, and this may differ from the value returned by WSAGetLastError().
Return Value The return value indicates the error code for this thread’s last WinSock operation that
failed.
4.34. WSAGetOverlappedResult()
Description Returns the results of an overlapped operation on the specified socket.
#include <winsock2.h>
BOOL WSAAPI
WSAGetOverlappedResult (
IN SOCKET s,
IN LPWSAOVERLAPPED lpOverlapped,
OUT LPDWORD lpcbTransfer,
IN BOOL fWait,
OUT LPDWORD lpdwFlags
);
s Identifies the socket. This is the same socket that was specified when
the overlapped operation was started by a call to WSARecv(),
WSARecvFrom(), WSASend(), WSASendTo(), or WSAIoctl().
lpcbTransfer Points to a 32-bit variable that receives the number of bytes that were
actually transferred by a send or receive operation, or by WSAIoctl().
fWait 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 event-based
completion notification.
lpdwFlags Points to a 32-bit variable that will receive one or more flags that
supplement the completion status. If the overlapped operation was
initiated via WSARecv() or WSARecvFrom(), this parameter will
contain the results value for lpFlags parameter.
Remarks The results reported by the WSAGetOverlappedResult() function are those of the
specified socket's last overlapped operation to which the specified WSAOVERLAPPED
structure was provided, and for which the operation's results were pending. A pending
operation is indicated when the function that started the operation returns
SOCKET_ERROR, and the WSAGetLastError() function returns WSA_IO_PENDING.
When an I/O operation 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 been completed, the system sets the event object to the signaled
state.
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 or the overlapped operation
completed but with errors, or that 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 of WSAGetOverlappedResult() or of the associated
overlapped operation).
WSA_IO_INCOMPLETE fWait is FALSE and the I/O operation has not yet
completed.
4.35. WSAGetQOSByName()
Description Initializes a QOS structure based on a named template, or retrieves an enumeration of the
available template names.
#include <winsock2.h>
BOOL WSAAPI
WSAGetQOSByName(
IN SOCKET s,
IN OUT LPWSABUF lpQOSName,
OUT LPQOS lpQOS
);
Remarks Applications may use this function to initialize a QOS structure to a set of known values
appropriate for a particular service class or media type. These values are stored in a
template which is referenced by a well-known name. The client may retrieve these values
by setting the buf member of the WSABUF indicated by lpQOSName to point to a string
of non-zero length specifying a template name. In this case the usage of lpQOSName is
IN only, and results are returned through lpQOS.
Alternatively, the client may use this function to retrieve an enumeration of available
template names. The client may do this by setting the buf member of the WSABUF
indicated by lpQOSName to a zero-length null-terminated string. In this case the buffer
indicated by buf is over-written with a sequence of as many null-terminated template
names are available up to the number of bytes available in buf as indicated by the len
member of the WSABUF indicated by lpQOSName. The list of names itself is terminated
by a zero-length name. When WSAGetQOSByName() is used to retrieve template
names, the lpQOS parameter is ignored.
Return Value If the function succeeds, the return value is TRUE. If the function fails, the return value
is FALSE. To get extended error information, call WSAGetLastError().
4.36. WSAHtonl()
Description Convert a u_long from host byte order to network byte order.
#include <winsock2.h>
int WSAAPI
WSAHtonl (
IN SOCKET s,
IN u_long hostlong,
OUT u_long FAR * lpnetlong
);
Remarks This routine takes a 32-bit number in host byte order and returns a 32-bit number pointed
to by the lpnetlong parameter in the network byte order associated with socket s.
4.37. WSAHtons()
Description Convert a u_short from host byte order to network byte order.
#include <winsock2.h>
int WSAAPI
WSAHtons (
IN SOCKET s,
IN u_short hostshort,
OUT u_short FAR * lpnetshort
);
Remarks This routine takes a 16-bit number in host byte order and returns a 16-bit number pointed
to by the lpnetshort parameter in the network byte order associated with socket s.
4.38. WSAIoctl()
Description Control the mode of a socket.
#include <winsock2.h>
int WSAAPI
WSAIoctl (
IN SOCKET s,
IN DWORD dwIoControlCode,
IN LPVOID lpvInBuffer,
IN DWORD cbInBuffer,
OUT LPVOID lpvOutBuffer,
IN DWORD cbOutBuffer,
OUT LPDWORD lpcbBytesReturned,
IN LPWSAOVERLAPPED lpOverlapped,
IN LPWSAOVERLAPPED_COMPLETION_ROUTINE
lpCompletionRoutine
);
s Handle to a socket
Remarks This routine is used to set or retrieve operating parameters associated with the socket, the
transport protocol, or the communications subsystem.
If both lpOverlapped and lpCompletionRoutine are NULL, the socket in this function will
be treated as a non-overlapped socket.
Any ioctl may block indefinitely, depending on the service provider’s implementation. If
the application cannot tolerate blocking in a WSAIoctl() call, overlapped I/O would be
advised for ioctls that are especially likely to block including:
SIO_FINDROUTE
SIO_FLUSH
SIO_GET_QOS
SIO_GET_GROUP_QOS
SIO_SET_QOS
SIO_SET_GROUP_QOS
SIO_ROUTING_INTERFACE_CHANGE
SIO_ADDRESS_LIST_CHANGE
Some protocol-specific ioctls may also be especially likely to block. Check the relevant
protocol-specific annex for any available information.
3 3 2 2 2 2 2 2 2 2 2 2 1 1 1 1 1 1 1 1 1 1
1 0 9 8 7 6 5 4 3 2 1 0 9 8 7 6 5 4 3 2 1 0 9 8 7 6 5 4 3 2 1 0
I O V T Vendor/Address Family Code
I is set if the input buffer is valid for the code, as with IOC_IN.
O is set if the output buffer is valid for the code, as with IOC_OUT. Note that for codes
with both input and output parameters, both I and O will be set.
T is a two-bit quantity which defines the type of ioctl. The following values are defined:
0 - The ioctl is a standard Unix ioctl code, as with FIONREAD, FIONBIO, etc.
1 - The ioctl is a generic Windows Sockets 2 ioctl code. New ioctl codes defined
for Windows Sockets 2 will have T == 1.
3 - The ioctl applies only to a specific vendor's provider. This type allows
companies to be assigned a vendor number which appears in the
Vendor/Address Family field, and then the vendor can define new ioctls
specific to that vendor without having to register the ioctl with a clearinghouse,
thereby providing vendor flexibility and privacy.
WSAIoctl 135
Vendor/Address Family- An 11-bit quantity which defines the vendor who owns the
code (if T == 3) or which contains the address family to which the code applies (if T ==
2). If this is a Unix ioctl code (T == 0) then this field has the same value as the code on
Unix. If this is a generic Windows Sockets 2 ioctl (T == 1) then this field can be used as
an extension of the "code" field to provide additional code values.
Code - A 16-bit quantity that contains the specific ioctl code for the operation (i.e. the
command).
Command Semantics
FIONREAD Determine the amount of data which can be read atomically from socket
s. lpvOutBuffer points at an unsigned long in which WSAIoctl() stores
the result. If s is stream-oriented (e.g., type SOCK_STREAM),
FIONREAD returns the total amount of data which may be read in a
single receive operation; this is normally the same as the total amount
of data queued on the socket, but since data stream is byte-oriented, this
is not guaranteed. If s is message-oriented (e.g., type SOCK_DGRAM),
FIONREAD returns the size of the first datagram (message) queued on
the socket.
SIOCATMARK Determine whether or not all out-of-band data has been read. This
applies only to a socket of stream style (e.g., type SOCK_STREAM)
which has been configured for in-line reception of any out-of-band data
(SO_OOBINLINE). If no out-of-band data is waiting to be read, the
operation returns TRUE. Otherwise it returns FALSE, and the next
receive operation performed on the socket will retrieve some or all of
the data preceding the "mark"; the application should use the
SIOCATMARK operation to determine whether any remains. If there is
any normal data preceding the "urgent" (out of band) data, it will be
received in order. (Note that receive operations will never mix out-of-
band and normal data in the same call.) lpvOutBuffer points at a BOOL
in which WSAIoctl() stores the result.
Command Semantics
INT iAddressCount;
SOCKET_ADDRESS Address[1];
} SOCKET_ADDRESS_LIST, FAR *
LPSOCKET_ADDRESS_LIST;
Members:
iAddressCount - number of address structures in the list;
Address - array of protocol family specific address
structures.
When called with an overlapped socket, the lpOverlapped parameter must be valid for the
duration of the overlapped operation. The WSAOVERLAPPED structure has the
following form:
If lpCompletionRoutine is not NULL, the hEvent field is ignored and can be used by the
application to pass context information to the completion routine. A caller that passes a
non-NULL lpCompletionRoutine and later calls WSAGetOverlappedResult() for the
same overlapped IO request may not set the fWait parameter for that invocation of
WSAGetOverlappedResult() to TRUE. In this case the usage of the hEvent field is
undefined, and attempting to wait on the hEvent field would produce unpredictable
results.
void CALLBACK
CompletionRoutine(
IN DWORD dwError,
IN DWORD cbTransferred,
IN LPWSAOVERLAPPED lpOverlapped,
IN DWORD dwFlags
);
Returning from this function allows invocation of another pending completion routine for
this socket. The completion routines may be called in any order, not necessarily in the
same order the overlapped operations are completed.
142 WSAIoctl
Compatibility The ioctl codes with T == 0 are a subset of the ioctl codes used in Berkeley sockets. In
particular, there is no command which is equivalent to FIOASYNC.
Return Value Upon successful completion, the WSAIoctl () returns 0. Otherwise, a value of
SOCKET_ERROR is returned, and a specific error code may be retrieved by calling
WSAGetLastError().
Error Codes
4.39. WSAIsBlocking()
Description Determine if a blocking call is in progress. WSAIsBlocking() is only available for
WinSock 1.1 apps (that is, if at least one thread within the process negotiates version 1.0
or 1.1 at WSAStartup()).
Important Note: This function is for backwards compatibility with WinSock 1.1 and is
not considered part of the WinSock 2 specification. WinSock 2 applications should not
use this function.
#include <winsock2.h>
Remarks This function allows a WinSock 1.1 application to determine if it is executing while
waiting for a previous blocking call to complete.
Return Value The return value is TRUE if there is an outstanding blocking function awaiting
completion in the current thread. Otherwise, it is FALSE.
Comments In 16-bit WinSock 1.1 environments, although a call issued on a blocking socket appears
to an application program as though it "blocks", the WinSock DLL has to relinquish the
processor to allow other applications to run. This means that it is possible for the
application which issued the blocking call to be re-entered, depending on the message(s)
it receives. In this instance, the WSAIsBlocking() function can be used to ascertain
whether the task has been re-entered while waiting for an outstanding blocking call to
complete. Note that WinSock 1.1 prohibits more than one outstanding call per thread.
4.40. WSAJoinLeaf()
Description Join a leaf node into a multipoint session, exchange connect data, and specify needed
quality of service based on the supplied flow specs.
#include <winsock2.h>
SOCKET WSAAPI
WSAJoinLeaf (
IN SOCKET s,
IN const struct sockaddr FAR * name,
IN int namelen,
IN LPWSABUF lpCallerData,
OUT LPWSABUF lpCalleeData,
IN LPQOS lpSQOS,
IN LPQOS lpGQOS,
IN DWORD dwFlags
);
lpCallerData A pointer to the user data that is to be transferred to the peer during
multipoint session establishment.
lpCalleeData A pointer to the user data that is to be transferred back from the peer
during multipoint session establishment.
lpSQOS A pointer to the flow specs for socket s, one for each direction.
lpGQOS Reserved for future use with socket groups: A pointer to the flow specs
for the socket group (if applicable).
dwFlags Flags to indicate that the socket is acting as a sender, receiver, or both.
Remarks This function is used to join a leaf node to a multipoint session, and to perform a number
of other ancillary operations that occur at session join time as well. If the socket, s, is
unbound, unique values are assigned to the local association by the system, and the socket
is marked as bound.
WSAJoinLeaf() has the same parameters and semantics as WSAConnect() except that it
returns a socket descriptor (as in WSAAccept()), and it has an additional dwFlags
parameter. Only multipoint sockets created using WSASocket() with appropriate
multipoint flags set may be used for input parameter s in this function. The returned
socket descriptor will not be useable until after the join operation completes (e.g. if the
socket is in non-blocking mode, after a corresponding FD_CONNECT indication has
been received from WSAAsyncSelect() or WSAEventSelect() on the original socket s),
except that closesocket() may be invoked on this new socket descriptor to cancel a
pending join operation. A root application in a multipoint session may call
WSAJoinLeaf() one or more times in order to add a number of leaf nodes, however at
WSAJoinLeaf 145
most one multipoint connection request may be outstanding at a time. Refer to Appendix
B. Multipoint and Multicast Semantics for additional information.
For non-blocking sockets it is often not possible to complete the connection immediately.
In such a case, this function returns an as-yet unusable socket descriptor and the operation
proceeds. There is no error code such as WSAEWOULDBLOCK in this case, since the
function has effectively returned a “successful start” indication. When the final outcome
success or failure becomes known, it may be reported through WSAAsyncSelect() or
WSAEventSelect() depending on how the client registers for notification on the original
socket s. In either case, the notification is announced with FD_CONNECT and the error
code associated with the FD_CONNECT indicates either success or a specific reason for
failure. Note that select() cannot be used to detect completion notification for
WSAJoinLeaf().
When WSAJoinLeaf() is invoked with a c_leaf socket, the name parameter contains the
address of the root application (for a rooted control scheme) or an existing multipoint
session (non-rooted control scheme), and the returned socket descriptor is the same as the
input socket descriptor. In other words, a new socket descriptor is not allocated. In a
rooted control scheme, the root application would put its c_root socket in the listening
mode by calling listen(). The standard FD_ACCEPT notification will be delivered when
the leaf node requests to join itself to the multipoint session. The root application uses the
usual accept()/WSAAccept() functions to admit the new leaf node. The value returned
from either accept() or WSAAccept() is also a c_leaf socket descriptor just like those
returned from WSAJoinLeaf(). To accommodate multipoint schemes that allow both
root-initiated and leaf-initiated joins, it is acceptable for a c_root socket that is already in
listening mode to be used as an input to WSAJoinLeaf().
The application is responsible for allocating any memory space pointed to directly or
indirectly by any of the parameters it specifies.
The lpCallerData is a value parameter which contains any user data that is to be sent
along with the multipoint session join request. If lpCallerData is NULL, no user data
will be passed to the peer. The lpCalleeData is a result parameter which will contain any
user data passed back from the peer as part of the multipoint session establishment.
lpCalleeData->len initially contains the length of the buffer allocated by the application
and pointed to by lpCalleeData->buf. lpCalleeData->len will be set to 0 if no user data
has been passed back. The lpCalleeData information will be valid when the multipoint
join operation is complete. For blocking sockets, this will be when the WSAJoinLeaf()
function returns. For non-blocking sockets, this will be after the join operation has
146 WSAJoinLeaf
completed (e.g. after FD_CONNECT notification has occurred on the original socket s).
If lpCalleeData is NULL, no user data will be passed back. The exact format of the user
data is specific to the address family to which the socket belongs.
At multipoint session establishment time, an application may use the lpSQOS and/or
lpGQOS parameters to override any previous QOS specification made for the socket via
WSAIoctl() with either the SIO_SET_QOS or SIO_SET_GROUP_QOS opcodes.
lpSQOS specifies the flow specs for socket s, one for each direction, followed by any
additional provider-specific parameters. If either the associated transport provider in
general or the specific type of socket in particular cannot honor the QOS request, an error
will be returned as indicated below. The sending or receiving flow spec values will be
ignored, respectively, for any unidirectional sockets. If no provider-specific parameters
are supplied, the buf and len fields of lpSQOS->ProviderSpecific should be set to NULL
and 0, respectively. A NULL value for lpSQOS indicates no application supplied QOS.
Reserved for future use with socket groups: lpGQOS specifies the flow specs for the
socket group (if applicable), one for each direction, followed by any additional provider-
specific parameters. If no provider-specific parameters are supplied, the buf and len
fields of lpGQOS->ProviderSpecific should be set to NULL and 0, respectively. A NULL
value for lpGQOS indicates no application-supplied group QOS. This parameter will be
ignored if s is not the creator of the socket group.
The dwFlags parameter is used to indicate whether the socket will be acting only as a
sender (JL_SENDER_ONLY), only as a receiver (JL_RECEIVER_ONLY), or both
(JL_BOTH).
Comments When connected sockets break (i.e. become closed for whatever reason), they should be
discarded and recreated. It is safest to assume that when things go awry for any reason
on a connected socket, the application must discard and recreate the needed sockets in
order to return to a stable point.
Return Value If no error occurs, WSAJoinLeaf() returns a value of type SOCKET which is a descriptor
for the newly created multipoint socket. Otherwise, a value of INVALID_SOCKET is
returned, and a specific error code may be retrieved by calling WSAGetLastError().
On a blocking socket, the return value indicates success or failure of the join operation.
Also, until the multipoint session join attempt completes all subsequent calls to
WSAJoinLeaf() on the same socket will fail with the error code WSAEALREADY.
After the WSAJoinLeaf() completes successfully a subsequent attempt will usually fail
with the error code WSAEISCONN. An exception to the WSAEISCONN rule occurs for
a c_root socket that allows root-initiated joins. In such a case another join may be
initiated after a prior WSAJoinLeaf() completes.
WSAJoinLeaf 147
If the return error code indicates the multipoint session join attempt failed (i.e.
WSAECONNREFUSED, WSAENETUNREACH, WSAETIMEDOUT) the application
may call WSAJoinLeaf() again for the same socket.
4.41. WSANtohl()
Description Convert a u_long from network byte order to host byte order.
#include <winsock2.h>
int WSAAPI
WSANtohl (
IN SOCKET s,
IN u_long netlong,
OUT u_long FAR * lphostlong
);
Remarks This routine takes a 32-bit number in the network byte order associated with socket s and
returns a 32-bit number pointed to by the lphostlong parameter in host byte order.
4.42. WSANtohs()
Description Convert a u_short from network byte order to host byte order.
#include <winsock2.h>
int WSAAPI
WSANtohs (
IN SOCKET s,
IN u_short netshort,
OUT u_short FAR * lphostshort
);
Remarks This routine takes a 16-bit number in the network byte order associated with socket s and
returns a 16-bit number pointed to by the lphostshort parameter in host byte order.
4.43. WSARecv()
Description Receive data from a connected socket
#include <winsock2.h>
int WSAAPI
WSARecv (
IN SOCKET s,
IN OUT LPWSABUF lpBuffers,
IN DWORD dwBufferCount,
OUT LPDWORD lpNumberOfBytesRecvd,
IN OUT LPDWORD lpFlags,
IN LPWSAOVERLAPPED lpOverlapped,
IN LPWSAOVERLAPPED_COMPLETION_ROUTINE
lpCompletionRoutine
);
Remarks This function provides functionality over and above the standard recv() function in three
important areas:
• It can be used in conjunction with overlapped sockets to perform overlapped receive
operations.
• It allows multiple receive buffers to be specified making it applicable to the
scatter/gather type of I/O.
• The lpFlags parameter is both an INPUT and an OUTPUT parameter, allowing
applications to sense the output state of the MSG_PARTIAL flag bit. Note however,
that the MSG_PARTIAL flag bit is not supported by all protocols.
152 WSARecv
For connected, connectionless sockets, this function restricts the addresses from which
received messages are accepted. The function only returns messages from the remote
address specified in the connection. Messages from other addresses are (silently)
discarded.
For overlapped sockets WSARecv() is used to post one or more buffers into which
incoming data will be placed as it becomes available, after which the application-
specified completion indication (invocation of the completion routine or setting of an
event object) occurs. If the operation does not complete immediately, the final completion
status is retrieved via the completion routine or WSAGetOverlappedResult().
If both lpOverlapped and lpCompletionRoutine are NULL, the socket in this function will
be treated as a non-overlapped socket.
For non-overlapped sockets, the blocking semantics are identical to that of the standard
recv() function and the lpOverlapped and lpCompletionRoutine parameters are ignored.
Any data which has already been received and buffered by the transport will be copied
into the supplied user buffers. For the case of a blocking socket with no data currently
having been received and buffered by the transport, the call will block until data is
received. WinSock 2 does not define any standard blocking timeout mechanism for this
function. For protocols acting as byte-stream protocols the stack tries to return as much
data as possible subject to the supplied buffer space and amount of received data
available. However, receipt of a single byte is sufficient to unblock the caller. There is
no guarantee that more than a single byte will be returned. For protocols acting as
message-oriented, a full message is required to unblock the caller.
The supplied buffers are filled in the order in which they appear in the array pointed to by
lpBuffers, and the buffers are packed so that no holes are created.
responsibility to capture these WSABUF structures before returning from this call. This
enables applications to build stack-based WSABUF arrays.
For byte stream style sockets (e.g., type SOCK_STREAM), incoming data is placed into
the buffers until the buffers are filled, the connection is closed, or internally buffered data
is exhausted. Regardless of whether or not the incoming data fills all the buffers, the
completion indication occurs for overlapped sockets.
For connection-oriented sockets, WSARecv() can indicate the graceful termination of the
virtual circuit in one of two ways, depending on whether the socket is a byte stream or
message-oriented. For byte streams, zero bytes having been read (as indicated by zero
return value to indicate success, and lpNumberOfBytesRecvd value of zero) indicates
graceful closure and that no more bytes will ever be read. For message-oriented sockets,
where a zero byte message is often allowable, a failure with an error code of
WSAEDISCON is used to indicate graceful closure. In any case, a failure with an error
code of WSAECONNRESET indicates an abortive close has occurred.
lpFlags may be used to influence the behavior of the function invocation beyond the
options specified for the associated socket. That is, the semantics of this function are
determined by the socket options and the lpFlags parameter. The latter is constructed by
or-ing any of the following values:
Value Meaning
MSG_PEEK Peek at the incoming data. The data is copied into the buffer but is not
removed from the input queue. This flag is valid only for non-
overlapped sockets.
MSG_OOB Process out-of-band data (See section 3.5. Out-Of-Band data for a
discussion of this topic.)
For message-oriented sockets, the MSG_PARTIAL bit is set in the lpFlags parameter if a
partial message is received. If a complete message is received, MSG_PARTIAL is
cleared in lpFlags. In the case of delayed completion, the value pointed to by lpFlags is
not updated. When completion has been indicated the application should call
WSAGetOverlappedResult() and examine the flags pointed to by the lpdwFlags
parameter.
This function may be called from within the completion routine of a previous
WSARecv(), WSARecvFrom(), WSASend() or WSASendTo() function. For a given
socket, I/O completion routines will not be nested. This permits time-sensitive data
transmissions to occur entirely within a preemptive context.
The lpOverlapped parameter must be valid for the duration of the overlapped operation.
If multiple I/O operations are simultaneously outstanding, each must reference a separate
overlapped structure. The WSAOVERLAPPED structure has the following form:
If lpCompletionRoutine is not NULL, the hEvent field is ignored and can be used by the
application to pass context information to the completion routine. A caller that passes a
non-NULL lpCompletionRoutine and later calls WSAGetOverlappedResult() for the
same overlapped IO request may not set the fWait parameter for that invocation of
WSAGetOverlappedResult() to TRUE. In this case the usage of the hEvent field is
undefined, and attempting to wait on the hEvent field would produce unpredictable
results.
The completion routine follows the same rules as stipulated for Win32 file I/O completion
routines. The completion routine will not be invoked until the thread is in an alertable
wait state such as can occur when the function WSAWaitForMultipleEvents() with the
fAlertable parameter set to TRUE is invoked.
WSARecv 155
Transport providers allow an application to invoke send and receive operations from
within the context of the socket I/O completion routine, and guarantee that, for a given
socket, I/O completion routines will not be nested. This permits time-sensitive data
transmissions to occur entirely within a preemptive context.
void CALLBACK
CompletionRoutine(
IN DWORD dwError,
IN DWORD cbTransferred,
IN LPWSAOVERLAPPED lpOverlapped,
IN DWORD dwFlags
);
Returning from this function allows invocation of another pending completion routine for
this socket. When using WSAWaitForMultipleEvents(), all waiting completion
routines are called before the alertable thread’s wait is satisfied with a return code of
WSA_IO_COMPLETION. The completion routines may be called in any order, not
necessarily in the same order the overlapped operations are completed. However, the
posted buffers are guaranteed to be filled in the same order they are supplied.
Return Value If no error occurs and the receive operation has completed immediately, WSARecv()
returns 0. Note that in this case the completion routine will have already been scheduled,
and to be called once the calling thread is in the alertable state. Otherwise, a value of
SOCKET_ERROR is returned, and a specific error code may be retrieved by calling
WSAGetLastError(). The error code WSA_IO_PENDING indicates that the
overlapped operation has been successfully initiated and that completion will be indicated
at a later time. Any other error code indicates that the overlapped operation was not
successfully initiated and no completion indication will occur.
WSAEMSGSIZE The message was too large to fit into the specified
buffer and (for unreliable protocols only) any trailing
portion of the message that did not fit into the buffer
has been discarded.
WSAEINVAL The socket has not been bound (e.g., with bind()),.
4.44. WSARecvDisconnect()
Description Terminate reception on a socket, and retrieve the disconnect data if the socket is
connection-oriented.
#include <winsock2.h>
int WSAAPI
WSARecvDisconnect (
IN SOCKET s,
OUT LPWSABUF lpInboundDisconnectData
);
After this function has been successfully issued, subsequent receives on the socket will be
disallowed. This has no effect on the lower protocol layers. For TCP sockets, if there is
still data queued on the socket waiting to be received, or data arrives subsequently, the
connection is reset, since the data cannot be delivered to the user. For UDP, incoming
datagrams are accepted and queued. In no case will an ICMP error packet be generated.
Note that WSARecvDisconnect() does not close the socket, and resources attached to the
socket will not be freed until closesocket() is invoked.
Comments WSARecvDisconnect() does not block regardless of the SO_LINGER setting on the
socket.
An application should not rely on being able to re-use a socket after it has been
WSARecvDisconnect()ed. In particular, a WinSock provider is not required to support
the use of connect()/WSAConnect() on such a socket.
4.45. WSARecvFrom()
Description Receive a datagram and store the source address.
#include <winsock2.h>
int WSAAPI
WSARecvFrom (
IN SOCKET s,
IN OUT LPWSABUF lpBuffers,
IN DWORD dwBufferCount,
OUT LPDWORD lpNumberOfBytesRecvd,
IN OUT LPDWORD lpFlags,
OUT struct sockaddr FAR * lpFrom,
IN OUT LPINT lpFromlen,
IN LPWSAOVERLAPPED lpOverlapped,
IN LPWSAOVERLAPPED_COMPLETION_ROUTINE
lpCompletionRoutine
);
Remarks This function provides functionality over and above the standard recvfrom() function in
three important areas:
160 WSARecvFrom
For overlapped sockets, this function is used to post one or more buffers into which
incoming data will be placed as it becomes available on a (possibly connected) socket,
after which the application-specified completion indication (invocation of the completion
routine or setting of an event object) occurs. If the operation does not complete
immediately, the final completion status is retrieved via the completion routine or
WSAGetOverlappedResult(). Also note that the values pointed to by lpFrom and
lpFromlen are not updated until completion is indicated. Applications must not use or
disturb these values until they have been updated, therefore the application must not use
automatic (i.e. stack-based) variables for these parameters.
If both lpOverlapped and lpCompletionRoutine are NULL, the socket in this function will
be treated as a non-overlapped socket.
For non-overlapped sockets, the blocking semantics are identical to that of the standard
WSARecv() function and the lpOverlapped and lpCompletionRoutine parameters are
ignored. Any data which has already been received and buffered by the transport will be
copied into the supplied user buffers. For the case of a blocking socket with no data
currently having been received and buffered by the transport, the call will block until data
is received.
The supplied buffers are filled in the order in which they appear in the array pointed to by
lpBuffers, and the buffers are packed so that no holes are created.
For connectionless socket types, the address from which the data originated is copied to
the buffer pointed by lpFrom. The value pointed to by lpFromlen is initialized to the size
of this buffer, and is modified on completion to indicate the actual size of the address
stored there. As noted previously for overlapped sockets, the lpFrom and lpFromlen
parameters are not updated until after the overlapped I/O has completed. The memory
pointed to by these parameters must, therefore, remain available to the service provider
and cannot be allocated on the application’s stack frame. The lpFrom and lpFromlen
parameters are ignored for connection-oriented sockets.
For byte stream style sockets (e.g., type SOCK_STREAM), incoming data is placed into
the buffers until the buffers are filled, the connection is closed, or internally buffered data
WSARecvFrom 161
is exhausted. Regardless of whether or not the incoming data fills all the buffers, the
completion indication occurs for overlapped sockets. For message-oriented sockets, an
incoming message is placed into the supplied buffers, up to the total size of the buffers
supplied, and the completion indication occurs for overlapped sockets. If the message is
larger than the buffers supplied, the buffers are filled with the first part of the message. If
the MSG_PARTIAL feature is supported by the underlying service provider, the
MSG_PARTIAL flag is set in lpFlags and subsequent receive operation(s) will retrieve
the rest of the message. If MSG_PARTIAL is not supported but the protocol is reliable,
WSARecvFrom() generates the error WSAEMSGSIZE and a subsequent receive
operation with a larger buffer can be used to retrieve the entire message. Otherwise (i.e.
the protocol is unreliable and does not support MSG_PARTIAL), the excess data is lost,
and WSARecvFrom() generates the error WSAEMSGSIZE.
lpFlags may be used to influence the behavior of the function invocation beyond the
options specified for the associated socket. That is, the semantics of this function are
determined by the socket options and the lpFlags parameter. The latter is constructed by
or-ing any of the following values:
Value Meaning
MSG_PEEK Peek at the incoming data. The data is copied into the buffer but is not
removed from the input queue. This flag is valid only for non-
overlapped sockets.
MSG_OOB Process out-of-band data (See section 3.5. Out-Of-Band data for a
discussion of this topic.)
For message-oriented sockets, the MSG_PARTIAL bit is set in the lpFlags parameter if a
partial message is received. If a complete message is received, MSG_PARTIAL is
cleared in lpFlags. In the case of delayed completion, the value pointed to by lpFlags is
not updated. When completion has been indicated the application should call
WSAGetOverlappedResult() and examine the flags pointed to by the lpdwFlags
parameter.
parameter in the completion routine (if specified), or via the lpcbTransfer parameter in
WSAGetOverlappedResult(). Flag values are obtained either via the dwFlags parameter
of the completion routine, or by examining the lpdwFlags parameter of
WSAGetOverlappedResult().
This function may be called from within the completion routine of a previous
WSARecv(), WSARecvFrom(), WSASend() or WSASendTo() function. For a given
socket, I/O completion routines will not be nested. This permits time sensitive data
transmissions to occur entirely within a preemptive context.
The lpOverlapped parameter must be valid for the duration of the overlapped operation.
If multiple I/O operations are simultaneously outstanding, each must reference a separate
overlapped structure. The WSAOVERLAPPED structure has the following form:
If lpCompletionRoutine is not NULL, the hEvent field is ignored and can be used by the
application to pass context information to the completion routine. A caller that passes a
non-NULL lpCompletionRoutine and later calls WSAGetOverlappedResult() for the
same overlapped IO request may not set the fWait parameter for that invocation of
WSAGetOverlappedResult() to TRUE. In this case the usage of the hEvent field is
undefined, and attempting to wait on the hEvent field would produce unpredictable
results.
The completion routine follows the same rules as stipulated for Win32 file I/O completion
routines. The completion routine will not be invoked until the thread is in an alertable
wait state such as can occur when the function WSAWaitForMultipleEvents() with the
fAlertable parameter set to TRUE is invoked.
Transport providers allow an application to invoke send and receive operations from
within the context of the socket I/O completion routine, and guarantee that, for a given
socket, I/O completion routines will not be nested. This permits time-sensitive data
transmissions to occur entirely within a preemptive context.
void CALLBACK
CompletionRoutine(
IN DWORD dwError,
IN DWORD cbTransferred,
IN LPWSAOVERLAPPED lpOverlapped,
IN DWORD dwFlags
);
WSARecvFrom 163
Returning from this function allows invocation of another pending completion routine for
this socket. When using WSAWaitForMultipleEvents(), all waiting completion routines
are called before the alertable thread’s wait is satisfied with a return code of
WSA_IO_COMPLETION. The completion routines may be called in any order, not
necessarily in the same order the overlapped operations are completed. However, the
posted buffers are guaranteed to be filled in the same order they are supplied.
Return Value If no error occurs and the receive operation has completed immediately,
WSARecvFrom() returns 0. Note that in this case the completion routine will have
already been scheduled, and to be called once the calling thread is in the alertable state.
Otherwise, a value of SOCKET_ERROR is returned, and a specific error code may be
retrieved by calling WSAGetLastError(). The error code WSA_IO_PENDING
indicates that the overlapped operation has been successfully initiated and that completion
will be indicated at a later time. Any other error code indicates that the overlapped
operation was not successfully initiated and no completion indication will occur.
WSAEINVAL The socket has not been bound (e.g., with bind()).
WSAEMSGSIZE The message was too large to fit into the specified
buffer and (for unreliable protocols only) any trailing
portion of the message that did not fit into the buffer
has been discarded.
4.46. WSAResetEvent()
Description Resets the state of the specified event object to nonsignaled.
#include <winsock2.h>
BOOL WSAAPI
WSAResetEvent(
IN WSAEVENT hEvent
);
Return Value If the function succeeds, the return value is TRUE. If the function fails, the return value is
FALSE. To get extended error information, call WSAGetLastError().
4.47. WSASend()
Description Send data on a connected socket
#include <winsock2.h>
int WSAAPI
WSASend (
IN SOCKET s,
IN LPWSABUF lpBuffers,
IN DWORD dwBufferCount,
OUT LPDWORD lpNumberOfBytesSent,
IN DWORD dwFlags,
IN LPWSAOVERLAPPED lpOverlapped,
IN LPWSAOVERLAPPED_COMPLETION_ROUTINE
lpCompletionRoutine
);
lpNumberOfBytesSent A pointer to the number of bytes sent by this call if the I/O
operation completes immediately.
Remarks This function provides functionality over and above the standard send() function in two
important areas:
• It can be used in conjunction with overlapped sockets to perform overlapped send
operations.
• It allows multiple send buffers to be specified making it applicable to the
scatter/gather type of I/O.
WSASend() is used to write outgoing data from one or more buffers on a connection-
oriented socket specified by s. It may also be used, however, on connectionless sockets
WSASend 167
which have a stipulated default peer address established via the connect() or
WSAConnect() function.
If both lpOverlapped and lpCompletionRoutine are NULL, the socket in this function will
be treated as a non-overlapped socket.
For message-oriented sockets, care must be taken not to exceed the maximum message
size of the underlying provider, which can be obtained by getting the value of socket
option SO_MAX_MSG_SIZE. If the data is too long to pass atomically through the
underlying protocol the error WSAEMSGSIZE is returned, and no data is transmitted.
Note that the successful completion of a WSASend() does not indicate that the data was
successfully delivered.
dwFlags may be used to influence the behavior of the function invocation beyond the
options specified for the associated socket. That is, the semantics of this function are
determined by the socket options and the dwFlags parameter. The latter is constructed by
or-ing any of the following values:
Value Meaning
MSG_DONTROUTE
Specifies that the data should not be subject to routing. A WinSock
service provider may choose to ignore this flag.
MSG_PARTIAL Specifies that lpBuffers only contains a partial message. Note that the
error code WSAEOPNOTSUPP will be returned by transports which
do not support partial message transmissions.
168 WSASend
This function may be called from within the completion routine of a previous
WSARecv(), WSARecvFrom(), WSASend() or WSASendTo() function. This permits
time-sensitive data transmissions to occur entirely within a preemptive context.
The lpOverlapped parameter must be valid for the duration of the overlapped operation.
If multiple I/O operations are simultaneously outstanding, each must reference a separate
overlapped structure. The WSAOVERLAPPED structure has the following form:
If lpCompletionRoutine is not NULL, the hEvent field is ignored and can be used by the
application to pass context information to the completion routine. A caller that passes a
non-NULL lpCompletionRoutine and later calls WSAGetOverlappedResult() for the
same overlapped IO request may not set the fWait parameter for that invocation of
WSAGetOverlappedResult() to TRUE. In this case the usage of the hEvent field is
undefined, and attempting to wait on the hEvent field would produce unpredictable
results.
The completion routine follows the same rules as stipulated for Win32 file I/O completion
routines. The completion routine will not be invoked until the thread is in an alertable
wait state such as can occur when the function WSAWaitForMultipleEvents() with the
fAlertable parameter set to TRUE is invoked.
Transport providers allow an application to invoke send and receive operations from
within the context of the socket I/O completion routine, and guarantee that, for a given
socket, I/O completion routines will not be nested. This permits time-sensitive data
transmissions to occur entirely within a preemptive context.
void CALLBACK
CompletionRoutine(
IN DWORD dwError,
WSASend 169
IN DWORD cbTransferred,
IN LPWSAOVERLAPPED lpOverlapped,
IN DWORD dwFlags
);
Returning from this function allows invocation of another pending completion routine for
this socket. All waiting completion routines are called before the alertable thread’s wait
is satisfied with a return code of WSA_IO_COMPLETION. The completion routines
may be called in any order, not necessarily in the same order the overlapped operations
are completed. However, the posted buffers are guaranteed to be sent in the same order
they are supplied.
Return Value If no error occurs and the send operation has completed immediately, WSASend() returns
0. Note that in this case the completion routine will have already been scheduled, and to
be called once the calling thread is in the alertable state. Otherwise, a value of
SOCKET_ERROR is returned, and a specific error code may be retrieved by calling
WSAGetLastError(). The error code WSA_IO_PENDING indicates that the
overlapped operation has been successfully initiated and that completion will be indicated
at a later time. Any other error code indicates that the overlapped operation was not
successfully initiated and no completion indication will occur.
WSAEINVAL The socket has not been bound with bind(), or the
socket is not created with the overlapped flag.
4.48. WSASendDisconnect()
Description Initiate termination of the connection for the socket and send disconnect data.
#include <winsock2.h>
int WSAAPI
WSASendDisconnect (
IN SOCKET s,
IN LPWSABUF lpOutboundDisconnectData
);
After this function has been successfully issued, subsequent sends are disallowed.
Note that WSASendDisconnect() does not close the socket, and resources attached to the
socket will not be freed until closesocket() is invoked.
Comments WSASendDisconnect() does not block regardless of the SO_LINGER setting on the
socket.
An application should not rely on being able to re-use a socket after it has been
WSASendDisconnect()ed. In particular, a WinSock provider is not required to support
the use of connect()/WSAConnect() on such a socket.
4.49. WSASendTo()
Description Send data to a specific destination, using overlapped I/O where applicable.
#include <winsock2.h>
int WSAAPI
WSASendTo (
IN SOCKET s,
IN LPWSABUF lpBuffers,
IN DWORD dwBufferCount,
OUT LPDWORD lpNumberOfBytesSent,
IN DWORD dwFlags,
IN const struct sockaddr FAR * lpTo,
IN int iToLen,
IN LPWSAOVERLAPPED lpOverlapped,
IN LPWSAOVERLAPPED_COMPLETION_ROUTINE
lpCompletionRoutine
);
lpNumberOfBytesSent A pointer to the number of bytes sent by this call if the I/O
operation completes immediately.
Remarks This function provides functionality over and above the standard sendto() function in two
important areas:
• It can be used in conjunction with overlapped sockets to perform overlapped send
operations.
174 WSASendTo
If both lpOverlapped and lpCompletionRoutine are NULL, the socket in this function will
be treated as a non-overlapped socket.
For message-oriented sockets, care must be taken not to exceed the maximum message
size of the underlying transport, which can be obtained by getting the value of socket
option SO_MAX_MSG_SIZE. If the data is too long to pass atomically through the
underlying protocol the error WSAEMSGSIZE is returned, and no data is transmitted.
Note that the successful completion of a WSASendTo() does not indicate that the data
was successfully delivered.
dwFlags may be used to influence the behavior of the function invocation beyond the
options specified for the associated socket. That is, the semantics of this function are
determined by the socket options and the dwFlags parameter. The latter is constructed by
or-ing any of the following values:
Value Meaning
MSG_DONTROUTE
Specifies that the data should not be subject to routing. A WinSock
service provider may choose to ignore this flag.
WSASendTo 175
MSG_PARTIAL Specifies that lpBuffers only contains a partial message. Note that the
error code WSAEOPNOTSUPP will be returned by transports which
do not support partial message transmissions.
This function may be called from within the completion routine of a previous
WSARecv(), WSARecvFrom(), WSASend() or WSASendTo() function. This permits
time-sensitive data transmissions to occur entirely within a preemptive context.
The lpOverlapped parameter must be valid for the duration of the overlapped operation.
If multiple I/O operations are simultaneously outstanding, each must reference a separate
overlapped structure. The WSAOVERLAPPED structure has the following form:
If lpCompletionRoutine is not NULL, the hEvent field is ignored and can be used by the
application to pass context information to the completion routine. A caller that passes a
non-NULL lpCompletionRoutine and later calls WSAGetOverlappedResult() for the
same overlapped IO request may not set the fWait parameter for that invocation of
WSAGetOverlappedResult() to TRUE. In this case the usage of the hEvent field is
undefined, and attempting to wait on the hEvent field would produce unpredictable
results.
The completion routine follows the same rules as stipulated for Win32 file I/O completion
routines. The completion routine will not be invoked until the thread is in an alertable
wait state such as can occur when the function WSAWaitForMultipleEvents() with the
fAlertable parameter set to TRUE is invoked.
176 WSASendTo
Transport providers allow an application to invoke send and receive operations from
within the context of the socket I/O completion routine, and guarantee that, for a given
socket, I/O completion routines will not be nested. This permits time-sensitive data
transmissions to occur entirely within a preemptive context.
void CALLBACK
CompletionRoutine(
IN DWORD dwError,
IN DWORD cbTransferred,
IN LPWSAOVERLAPPED lpOverlapped,
IN DWORD dwFlags
);
Returning from this function allows invocation of another pending completion routine for
this socket. All waiting completion routines are called before the alertable thread’s wait
is satisfied with a return code of WSA_IO_COMPLETION. The completion routines
may be called in any order, not necessarily in the same order the overlapped operations
are completed. However, the posted buffers are guaranteed to be sent in the same order
they are supplied.
Return Value If no error occurs and the send operation has completed immediately, WSASendTo()
returns 0. Note that in this case the completion routine will have already been scheduled,
and to be called once the calling thread is in the alertable state. Otherwise, a value of
SOCKET_ERROR is returned, and a specific error code may be retrieved by calling
WSAGetLastError(). The error code WSA_IO_PENDING indicates that the
overlapped operation has been successfully initiated and that completion will be indicated
at a later time. Any other error code indicates that the overlapped operation was not
successfully initiated and no completion indication will occur.
WSAEINVAL The socket has not been bound with bind(), or the
socket is not created with the overlapped flag.
4.50. WSASetBlockingHook()
Description Establish an application-supplied blocking hook function. WSASetBlockingHook() is
only available for WinSock 1.1 apps (that is, if at least one thread within the process
negotiates version 1.0 or 1.1 at WSAStartup()).
Important Note: This function is for backwards compatibility with WinSock 1.1 and is
not considered part of the WinSock 2 specification. WinSock 2 applications should not
use this function.
#include <winsock2.h>
FARPROC WSAAPI
WSASetBlockingHook (
IN FARPROC lpBlockFunc
);
Remarks This function installs a new function which a WinSock implementation should use to
implement blocking socket function calls.
for(;;) {
/* Look for WinSock implementation’s messages (only */
/* necessary if WinSock uses messages internally) */
if (PeekMessage(&msg,hMyWnd,MYFIRST,MYLAST,PM_REMOVE) {
TranslateMessage(&msg);
DispatchMessage(&msg);
}
Note that WinSock implementations may perform the above steps in a different order; for
example, the check for operation complete may occur before calling the blocking hook.
The default BlockingHook() function is equivalent to:
180 WSASetBlockingHook
BOOL DefaultBlockingHook(void) {
MSG msg;
BOOL ret;
/* get the next message if any */
ret = (BOOL)PeekMessage(&msg,NULL,0,0,PM_REMOVE);
/* if we got one, process it */
if (ret) {/* TRUE if we got a message */
TranslateMessage(&msg);
DispatchMessage(&msg);
}
return ret;
}
Return Value The return value is a pointer to the procedure-instance of the previously installed blocking
function. The application or library that calls the WSASetBlockingHook () function
should save this return value so that it can be restored if necessary. (If "nesting" is not
important, the application may simply discard the value returned by
WSASetBlockingHook() and eventually use WSAUnhookBlockingHook() to restore
the default mechanism.) If the operation fails, a NULL pointer is returned, and a specific
error number may be retrieved by calling WSAGetLastError().
4.51. WSASetEvent()
Description Sets the state of the specified event object to signaled.
#include <winsock2.h>
BOOL WSAAPI
WSASetEvent(
IN WSAEVENT hEvent
);
If the function fails, the return value is FALSE. To get extended error information, call
WSAGetLastError().
4.52. WSASetLastError()
Description Set the error code which can be retrieved by WSAGetLastError().
#include <winsock2.h>
void WSAAPI
WSASetLastError (
IN int iError
);
Remarks This function allows an application to set the error code to be returned by a subsequent
WSAGetLastError() call for the current thread. Note that any subsequent WinSock
routine called by the application will override the error code as set by this routine.
The error code set by WSASetLastError() is different from the error code reset by
getsockopt() SO_ERROR.
4.53. WSASocket()
Description Create a socket which is bound to a specific transport service provider, optionally create
and/or join a socket group.
#include <winsock2.h>
SOCKET WSAAPI
WSASocket (
IN int af,
IN int type,
IN int protocol,
IN LPWSAPROTOCOL_INFO lpProtocolInfo,
IN GROUP g,
IN DWORD dwFlags
);
protocol A particular protocol to be used with the socket which is specific to the
indicated address family.
g Reserved for future use with socket groups: The identifier of the socket
group.
Remarks This function causes a socket descriptor and any related resources to be allocated and
associated with a transport service provider. By default, the created socket will not have
the overlapped attribute. If lpProtocolInfo is NULL, the WinSock 2 DLL uses the first
three parameters (af, type, protocol) to determine which service provider is used by
selecting the first transport provider able to support the stipulated address family, socket
type and protocol values. If the lpProtocolInfo is not NULL, the socket will be bound to
the provider associated with the indicated WSAPROTOCOL_INFO struct. In this
instance, the application may supply the manifest constant FROM_PROTOCOL_INFO as
the value for any of af, type or protocol. This indicates that the corresponding values from
the indicated WSAPROTOCOL_INFO struct (iAddressFamily, iSocketType, iProtocol)
are to be assumed. In any case, the values supplied for af, type and protocol are supplied
unmodified to the transport service provider via the corresponding parameters to the
WSPSocket() function in the SPI.
When selecting a protocol and its supporting service provider based on af, type and
protocol this procedure will only choose a base protocol or a protocol chain, not a
protocol layer by itself. Unchained protocol layers are not considered to have "partial
matches" on type or af either. That is, they do not lead to an error code of
WSAEAFNOSUPPORT or WSAEPROTONOSUPPORT if no suitable protocol is found.
184 WSASocket
Note: the manifest constant AF_UNSPEC continues to be defined in the header file but
its use is strongly discouraged, as this may cause ambiguity in interpreting the value of
the protocol parameter.
Reserved for future use with socket groups: Parameter g is used to indicate the
appropriate actions on socket groups:
if g is an existing socket group ID, join the new socket to this group, provided
all the requirements set by this group are met; or
if g = SG_UNCONSTRAINED_GROUP, create an unconstrained socket
group and have the new socket be the first member; or
if g = SG_CONSTRAINED_GROUP, create a constrained socket group and
have the new socket be the first member; or
if g = zero, no group operation is performed
For unconstrained groups, any set of sockets may be grouped together as long as they are
supported by a single service provider. A constrained socket group may consist only of
connection-oriented sockets, and requires that connections on all grouped sockets be to
the same address on the same host. For newly created socket groups, the new group ID
can be retrieved by using getsockopt() with option SO_GROUP_ID, if this operation
completes successfully. A socket group and its associated ID remain valid until the last
socket belonging to this socket group is closed. Socket group IDs are unique across all
processes for a given service provider.
The dwFlags parameter may be used to specify the attributes of the socket by or-ing any
of the following Flags:
Flag Meaning
WSA_FLAG_OVERLAPPED
This flag causes an overlapped socket to be created. Overlapped
sockets may utilize WSASend(), WSASendTo(), WSARecv(),
WSARecvFrom() and WSAIoctl() for overlapped I/O operations,
which allows multiple these operations to be initiated and in progress
simultaneously. All functions that allow overlapped operation
(WSASend(), WSARecv(),WSASendTo(), WSARecvFrom(),
WSAIoctl()) also support non-overlapped usage on an overlapped
socket if the values for parameters related to overlapped operation are
NULL.
WSA_FLAG_MULTIPOINT_C_ROOT
Indicates that the socket created will be a c_root in a multipoint session.
Only allowed if a rooted control plane is indicated in the protocol’s
WSAPROTOCOL_INFO struct. Refer to Appendix B. Multipoint and
Multicast Semantics for additional information.
WSA_FLAG_MULTIPOINT_C_LEAF
Indicates that the socket created will be a c_leaf in a multicast session.
Only allowed if XP1_SUPPORT_MULTIPOINT is indicated in the
protocol’s WSAPROTOCOL_INFO struct. Refer to Appendix B.
Multipoint and Multicast Semantics for additional information.
WSA_FLAG_MULTIPOINT_D_ROOT
Indicates that the socket created will be a d_root in a multipoint session.
Only allowed if a rooted data plane is indicated in the protocol’s
WSAPROTOCOL_INFO struct. Refer to Appendix B. Multipoint and
Multicast Semantics for additional information.
WSASocket 185
WSA_FLAG_MULTIPOINT_D_LEAF
Indicates that the socket created will be a d_leaf in a multipoint session.
Only allowed if XP1_SUPPORT_MULTIPOINT is indicated in the
protocol’s WSAPROTOCOL_INFO struct. Refer to Appendix B.
Multipoint and Multicast Semantics for additional information.
Support for sockets with type RAW is not required but service providers are encouraged
to support raw sockets whenever it makes sense to do so.
Return Value If no error occurs, WSASocket() returns a descriptor referencing the new socket.
Otherwise, a value of INVALID_SOCKET is returned, and a specific error code may be
retrieved by calling WSAGetLastError().
See Also accept(), bind(), connect(), getsockname(), getsockopt(), setsockopt(), listen(), recv(),
recvfrom(), select(), send(), sendto(), shutdown(), ioctlsocket().
WSAStartup 187
4.54. WSAStartup()
Description Initiate use of the WinSock DLL by a process.
#include <winsock2.h>
int WSAAPI
WSAStartup (
IN WORD wVersionRequested,
OUT LPWSADATA lpWSAData
);
wVersionRequested The highest version of WinSock support that the caller can
use. The high order byte specifies the minor version (revision)
number; the low-order byte specifies the major version
number.
Remarks This function MUST be the first WinSock function called by an application or DLL. It
allows an application or DLL to specify the version of WinSock required and to retrieve
details of the specific WinSock implementation. The application or DLL may only issue
further WinSock functions after a successful WSAStartup() invocation.
In order to support future WinSock implementations and applications which may have
functionality differences from current version of WinSock, a negotiation takes place in
WSAStartup(). The caller of WSAStartup() and the WinSock DLL indicate to each
other the highest version that they can support, and each confirms that the other's highest
version is acceptable. Upon entry to WSAStartup(), the WinSock DLL examines the
version requested by the application. If this version is equal to or higher than the lowest
version supported by the DLL, the call succeeds and the DLL returns in wHighVersion
the highest version it supports and in wVersion the minimum of its high version and
wVersionRequested. The WinSock DLL then assumes that the application will use
wVersion. If the wVersion field of the WSADATA structure is unacceptable to the caller,
it should call WSACleanup() and either search for another WinSock DLL or fail to
initialize.
Note that it is legal and possible for an application written to this version of the
specification to successfully negotiate a higher version number than the version of this
specification. In such a case, the application is only guaranteed access to higher-version
functionality that fits within the syntax defined in this version, such as new Ioctl codes
and new behavior of existing functions. New functions, for example, may be inaccessible.
To be guaranteed full access to new syntax of a future version, the application must fully
conform to that future version, such as compiling against a new header file, linking to a
new library, etc.
This negotiation allows both a WinSock DLL and a WinSock application to support a
range of WinSock versions. An application can successfully utilize a WinSock DLL if
there is any overlap in the version ranges. The following chart gives examples of how
WSAStartup() works in conjunction with different application and WinSock DLL
versions:
The following code fragment demonstrates how an application which supports only
version 2.2 of WinSock makes a WSAStartup() call:
WORD wVersionRequested;
WSADATA wsaData;
int err;
wVersionRequested = MAKEWORD( 2, 2 );
if ( LOBYTE( wsaData.wVersion ) != 2 ||
HIBYTE( wsaData.wVersion ) != 2 ) {
/* Tell the user that we couldn't find a useable */
/* WinSock DLL. */
WSACleanup( );
return;
}
Once an application or DLL has made a successful WSAStartup() call, it may proceed to
make other WinSock calls as needed. When it has finished using the services of the
WinSock DLL, the application or DLL must call WSACleanup() in order to allow the
WinSock DLL to free any resources for the application.
Details of the actual WinSock implementation are described in the WSAData structure
defined as follows:
struct WSAData {
WORD wVersion;
WORD wHighVersion;
char szDescription[WSADESCRIPTION_LEN+1];
char szSystemStatus[WSASYSSTATUS_LEN+1];
unsigned short iMaxSockets;
unsigned short iMaxUdpDg;
char FAR * lpVendorInfo;
};
WSAStartup 189
Note that an application should ignore the iMaxsockets, iMaxUdpDg, and lpVendorInfo
fields in WSAData if the value in wVersion after a successful call to WSAStartup() is at
least 2.0. This is because the architecture of WinSock has been changed in version 2.0 to
support multiple providers, and WSAData no longer applies to a single vendor’s stack.
Two new socket options are introduced to supply provider-specific information:
SO_MAX_MSG_SIZE (replaces the iMaxUdpDg element) and PVD_CONFIG (allows
any other provider-specific configuration to occur).
An application or DLL may call WSAStartup() more than once if it needs to obtain the
WSAData structure information more than once. On each such call the application may
specify any version number supported by the DLL.
Return Value WSAStartup() returns zero if successful. Otherwise it returns one of the error codes
listed below. Note that the normal mechanism whereby the application calls
WSAGetLastError() to determine the error code cannot be used, since the WinSock
DLL may not have established the client data area where the "last error" information is
stored.
4.55. WSAUnhookBlockingHook()
Description Restore the default blocking hook function. WSAUnhookBlockingHook() is only
available for WinSock 1.1 apps (that is, if at least one thread within the process negotiates
version 1.0 or 1.1 at WSAStartup()).
Important Note: This function is for backwards compatibility with WinSock 1.1 and is
not considered part of the WinSock 2 specification. WinSock 2 applications should not
use this function.
#include <winsock2.h>
Remarks This function removes any previous blocking hook that has been installed and reinstalls
the default blocking mechanism.
WSAUnhookBlockingHook() will always install the default mechanism, not the previous
mechanism. If an application wish to nest blocking hooks - i.e. to establish a temporary
blocking hook function and then revert to the previous mechanism (whether the default or
one established by an earlier WSASetBlockingHook()) - it must save and restore the
value returned by WSASetBlockingHook(); it cannot use
WSAUnhookBlockingHook().
Return Value The return value is 0 if the operation was successful. Otherwise the value
SOCKET_ERROR is returned, and a specific error number may be retrieved by calling
WSAGetLastError().
4.56. WSAWaitForMultipleEvents()
Description Returns either when any one or all of the specified event objects are in the signaled state,
or when the timeout interval expires.
#include <winsock2.h>
DWORD WSAAPI
WSAWaitForMultipleEvents(
IN DWORD cEvents,
IN const WSAEVENT FAR * lphEvents,
IN BOOL fWaitAll,
IN DWORD dwTimeout,
IN BOOL fAlertable
);
cEvents Specifies the number of event object handles in the array pointed to by
lphEvents. The maximum number of event object handles is
WSA_MAXIMUM_WAIT_EVENTS. One or more events must be
specified.
fWaitAll Specifies the wait type. If TRUE, the function returns when all event
objects in the lphEvents array are signaled at the same time. If FALSE,
the function returns when any one of the event objects is signaled. In
the latter case, the return value indicates the event object whose state
caused the function to return.
fAlertable Specifies whether the function returns when the system queues an I/O
completion routine for execution by the calling thread. If TRUE, the
completion routine is executed and the function returns. If FALSE, the
completion routine is not executed when the function returns.
Remarks WSAWaitForMultipleEvents() returns either when any one or when all of the specified
objects are in the signaled state, or when the time-out interval elapses. This function is
also used to perform an alertable wait by setting the parameter fAltertable to be TRUE.
This enables the function to return when the system queues an I/O completion routine to
be executed by the calling thread.
When fWaitAll is TRUE, the function’s wait condition is satisfied only when the state of
all objects is signaled at the same time. The function does not modify the state of the
specified objects until all objects are simultaneously signaled.
Applications that simply need to enter an alertable wait state without waiting for any
event objects to be signaled should use the Win32 SleepEx() function.
WSAWaitForMultipleEvents 193
Return Value If the function succeeds, the return value indicates the event object that caused the
function to return.
If the function fails, the return value is WSA_WAIT_FAILED. To get extended error
information, call WSAGetLastError().
Value Meaning
WAIT_IO_COMPLETION
One or more I/O completion routines are queued for execution.
WSA_WAIT_TIMEOUT
The time-out interval elapsed and the conditions specified by the
fWaitAll parameter are not satisfied.
4.57. WSAProviderConfigChange()
Description Notifies the application when the provider configuration is changed
#include <winsock2.h>
int WSAAPI
WSAProviderConfigChange(
IN OUTLPHANDLE lpNotificationHandle,
IN LPWSAOVERLAPPED lpOverlapped,
IN LPWSAOVERLAPPED_COMPLETION_ROUTINE
lpCompletionRoutine
);
The following sequence of actions can be used to guarantee that application always has
current protocol configuration information:
• call WSAProviderConfigChange
• call WSAEnumProtocols and/or WSAEnumNameSpaces
• whenever WSAProtocolConfigChange notifies application of provider configuration
change (via blocking or overlapped IO), the whole sequence of actions should be
repeated
• The ability of the client application to find the service within a name space and obtain the
required transport protocol and addressing information
For those accustomed to developing TCP/IP based applications, this may seem to involve little more than
looking up a host address and then using an agreed upon port number. Other networking schemes,
however, allow the location of the service, the protocol used for the service, and other attributes to be
discovered at run time. To accommodate the broad diversity of capabilities found in existing name
services, the WinSock 2 interface adopts the model described below.
Dynamic name spaces allow services to register with the name space on the fly, and for clients to discover
the available services at run time. Dynamic name spaces frequently rely on broadcasts to indicate the
continued availability of a network service. Examples of dynamic name spaces include the SAP name space
used within a Netware environment and the NBP name space used by Appletalk.
Static name spaces require all of the services to be registered ahead of time, i.e. when the name space is
created. The DNS is an example of a static name space. Although there is a programmatic way to resolve
names, there is no programmatic way to register names.
Persistent name spaces allow services to register with the name space on the fly. Unlike dynamic name
spaces however, persistent name spaces retain the registration information in non-volatile storage where it
remains until such time as the service requests that it be removed. Persistent name spaces are typified by
directory services such as X.500 and the NDS (Netware Directory Service). These environments allow the
adding, deleting, and modification of service properties. In addition, the service object representing the
Name Resolution and Registration 197
service within the directory service could have a variety of attributes associated with the service. The most
important attribute for client applications is the service’s addressing information.
WinSock 2 DLL
Note that it is possible for a given name space, say DNS, to have more than one name space provider
installed on a given machine.
As mentioned above, the generic term service refers to the server-half of a client/server application. In
WinSock, a service is associated with a service class, and each instance of a particular service has a service
name which must be unique within the service class. Examples of service classes include FTP Server, SQL
Server, XYZ Corp. Employee Info Server, etc. As the example attempts to illustrate, some service classes
are “well known” while others are very unique and specific to a particular vertical application. In either
case, every service class is represented by both a class name and a class ID. The class name does not
necessarily need to be unique, but the class ID must be. Globally Unique Identifiers (GUIDs) are used to
represent service class IDs. For well-known services, class names and class ID’s (GUIDs) have been pre-
allocated, and macros are available to convert between, for example, TCP port numbers (in host byte order)
and the corresponding class ID GUIDs. For other services, the developer chooses the class name and uses
the UUIDGEN.EXE utility to generate a GUID for the class ID.
The notion of a service class exists to allow a set of attributes to be established that are held in common by
all instances of a particular service. This set of attributes is provided at the time the service class is defined
to WinSock, and is referred to as the service class schema information. When a service is installed and
made available on a host machine, that service is considered instantiated, and its service name is used to
distinguish a particular instance of the service from other instances which may be known to the name space.
198 Name Resolution and Registration
Note that the installation of a service class only needs to occur on machines where the service executes, not
on all of the clients which may utilize the service. Where possible, the WinSock 2 DLL will provide service
class schema information to a name space provider at the time an instantiation of a service is to be
registered or a service query is initiated. The WinSock 2 DLL does not, of course, store this information
itself, but attempts to retrieve it from a name space provider that has indicated its ability to supply this data.
Since there is no guarantee that the WinSock 2 DLL will be able to supply the service class schema, name
space providers that need this information must have a fallback mechanism to obtain it through name space-
specific means.
As noted above, the Internet has adopted what can be termed a host-centric service model. Applications
needing to locate the transport address of a service generally must first resolve the address of a specific host
known to host the service. To this address they add in the well-known port number and thus create a
complete transport address. To facilitate the resolution of host names, a special service class identifier has
been pre-allocated (SVCID_HOSTNAME). A query that specifies SVCID_HOSTNAME as the service
class and uses the host name the service instance name will, if the query is successful, return host address
information.
In WinSock 2, applications that are protocol-independent wish to avoid the need to comprehend the internal
details of a transport address. Thus the need to first get a host address and then add in the port is
problematic. To avoid this, queries may also include the well-known name of a particular service and the
protocol over which the service operates, such as “ftp/tcp”. In this case, a successful query will return a
complete transport address for the specified service on the indicated host, and the application will not be
required to “crack open” a sockaddr structure. This is described in more detail below.
The Internet’s Domain Name System does not have a well-defined means to store service class schema
information. As a result, DNS name space providers will only be able to accommodate well-known TCP/IP
services for which a service class GUID has been preallocated. In practice this is not a serious limitation
since service class GUIDs have been preallocated for the entire set of TCP and UDP ports, and macros are
available to retrieve the GUID associated with any TCP or UDP port (with the port expressed in host byte
order). Thus all of the familiar services such as ftp, telnet, whois, etc. are well supported.
Continuing with our service class example, instance names of the ftp service may be “alder.intel.com” or
“rhino.microsoft.com” while an instance of the XYZ Corp. Employee Info Server might be named “XYZ
Corp. Employee Info Server Version 3.5”. In the first two cases, the combination of the service class GUID
for ftp and the machine name (supplied as the service instance name) uniquely identify the desired service.
In the third case, the host name where the service resides can be discovered at service query time, so the
service instance name does not need to include a host name.
When the required service class does not already exist, an application uses WSAInstallServiceClass() to
install a new service class by supplying a service class name, a GUID for the service class ID, and a series
of WSANSCLASSINFO structures. These structures are each specific to a particular name space, and
supply common values such as recommended TCP port numbers or Netware SAP Identifiers. A service
Name Resolution and Registration 199
class can be removed by calling WSARemoveServiceClass() and supplying the GUID corresponding to the
class ID.
Once a service class exists, specific instances of a service can be installed or removed via
WSASetService(). This function takes a WSAQUERYSET structure as an input parameter along with an
operation code and operation flags. The operation code indicates whether the service is being installed or
removed. The WSAQUERYSET structure provides all of the relevant information about the service
including service class ID, service name (for this instance), applicable name space identifier and protocol
information, and a set of transport addresses at which the service listens. Services should invoke
WSASetService() when they initialize in order to advertise their presence in dynamic name spaces.
The WSAEnumNameSpaceProviders() function allows an application to discover which name spaces are
accessible via WinSock’s name resolution facilities. It also allows an application to determine whether a
given name space is supported by more than one name space provider, and to discover the provider ID for
any particular name space provider. Using a provider ID, the application can restrict a query operation to a
specified name space provider.
WinSock’s name space query operations involves a series of calls: WSALookupServiceBegin(), followed
by one or more calls to WSALookupServiceNext() and ending with a call to WSALookupServiceEnd().
WSALookupServiceBegin() takes a WSAQUERYSET structure as input in order to define the query
parameters along with a set of flags to provide additional control over the search operation. It returns a
query handle which is used in the subsequent calls to WSALookupServiceNext() and
WSALookupServiceEnd().
The application invokes WSALookupServiceNext() to obtain query results, with results supplied in an
application-supplied WSAQUERYSET buffer. The application continues to call
WSALookupServiceNext() until the error code WSA_E_NO_MORE is returned indicating that all results
have been retrieved. The search is then terminated by a call to WSALookupServiceEnd(). The
WSALookupServiceEnd() function can also be used to cancel a currently pending
WSALookupServiceNext() when called from another thread.
In WinSock 2, conflicting error codes are defined for WSAENOMORE (10102) and WSA_E_NO_MORE
(10110). The error code WSAENOMORE will be removed in a future version and only
WSA_E_NO_MORE will remain. For WinSock 2, however, applications should check for both
WSAENOMORE and WSA_E_NO_MORE for the widest possible compatibility with Name Space
Providers that use either one.
The name resolution helper functions include a function to retrieve a service class name given a service
class ID, a pair of functions used to translate a transport address between a sockaddr struct and an ASCII
string representation, a function to retrieve the service class schema information for a given service class,
and a set of macros for mapping well known services to pre-allocated GUIDs.
200 Name Resolution and Registration
The following macros from winsock2.h aid in mapping between well known service classes and these name
spaces.
Query String
WSAQUERYSET
AFPROTOCOLS [ ]
iAddressFamily
iProtocol
CSADDR_INFO SOCKET_ADDRESS
LocalAddr lpSockaddr
RemoteAddr iSockaddrLength
iSocketType
iProtocol
SOCKADDR
sa_family
sa_data
Within the WSAQUERYSET structure, most of the fields are self explanatory, but some deserve additional
explanation. The dwSize field must always be filled in with sizeof(WSAQUERYSET), as this is used by
name space providers to detect and adapt to different versions of the WSAQUERYSET structure that may
appear over time.
The dwOutputFlags field is used by a name space provider to provide additional information about query
results. For details, see WSALookupServiceNext().
The WSAECOMPARATOR structure referenced by lpversion is used for both query constraint and results.
For queries, the dwVersion field indicates the desired version of the service. The ecHow field is an
enumerated type which specifies how the comparison will be made. The choices are COMP_EQUALS
which requires that an exact match in version occurs, or COMP_NOTLESS which specifies that the
service’s version number be no less than the value of dwVersion.
The interpretation of dwNameSpace and lpNSProviderId depends upon how the structure is being used and
is described further in the individual function descriptions that utilize this structure.
The lpszContext field applies to hierarchical name spaces, and specifies the starting point of a query or the
location within the hierarchy where the service resides. The general rules are:
Name Resolution and Registration 201
• A value of NULL, blank (“”) will start the search at the default context.
• A value of “\” starts the search at the top of the name space.
• Any other value starts the search at the designated point.
Providers that do not support containment may return an error if anything other than “” or “\” is specified.
Providers that support limited containment, such as groups, should accept “”, ‘\”, or a designated point.
Contexts are name space specific. If dwNameSpace is NS_ALL, then only “” or “\” should be passed as the
context since these are recognized by all name spaces.
The lpszQueryString field is used to supply additional, name space-specific query information such as a
string describing a well-known service and transport protocol name, as in “ftp/tcp”.
The AFPROTOCOLS structure referenced by lpafpProtocols is used for query purposes only, and supplies
a list of protocols to constrain the query. These protocols are represented as (address family, protocol)
pairs, since protocol values only have meaning within the context of an address family.
The array of CSADDR_INFO structure referenced by lpcsaBuffer contain all of the information needed to
for either a service to use in establishing a listen, or a client to use in establishing a connection to the
service. The LocalAddr and RemoteAddr fields both directly contain a SOCKET_ADDRESS structure. A
service would create a socket using the tuple (LocalAddr.lpSockaddr->sa_family, iSocketType, iProtocol).
It would bind the socket to a local address using LocalAddr.lpSockaddr, and LocalAddr.lpSockaddrLength.
The client creates its socket with the tuple (RemoteAddr.lpSockaddr->sa_family, iSocketType, iProtocol),
and uses the combination of RemoteAddr.lpSockaddr, and RemoteAddr.lpSockaddrLength when making a
remote connection.
WSAQUERYSET
Service Class ID (GUID)
WSASERVICECLASSINFO
lpServiceClassId
lpszServiceClassName
WSAQUERYSET
Service Class Name
dwCount
lpClassInfos
WSANSCLASSINFO WSAQUERYSET
Item Name
lpszName
dwNameSpace
dwValueType
dwValueSize
lpValue WSAQUERYSET
Item Value
For each service class, there is a single WSASERVICECLASSINFO structure. Within the
WSASERVICECLASSINFO structure, the service class’ unique identifier is contained in lpServiceClassId,
and an associated display string is referenced by lpServiceClassName. This is the string that will be
returned by WSAGetServiceClassNameByServiceClassId().
5.2.1. WSAAddressToString()
INT WSAAPI
WSAAddressToString(
IN LPSOCKADDR lpsaAddress,
IN DWORD dwAddressLength,
IN LPWSAPROTOCOL_INFO lpProtocolInfo,
OUT LPTSTR lpszAddressString,
IN OUT LPDWORD lpdwAddressStringLength
);
Return Value The return value is 0 if the operation was successful. Otherwise the value
SOCKET_ERROR is returned, and a specific error number may be retrieved by calling
WSAGetLastError().
WSA_NOT_ENOUGH_MEMORY
There was insufficient memory to perform the
operation.
WSAEnumNameSpaceProviders 205
5.2.2. WSAEnumNameSpaceProviders()
INT WSAAPI
WSAEnumNameSpaceProviders (
IN OUT LPDWORD lpdwBufferLength,
OUT LPWSANAMESPACE_INFO lpnspBuffer
);
Data Types The following data types are used in this call.
The WSANAMESPACE_INFO structure contains all of the registration information for
a name space provider.
Errors WSAEFAULT the buffer length was too small to receive all the
relevant WSANAMESPACE_INFO structures and
associated information. Pass in a buffer at least as
large as the value returned in lpdwBufferLength.
WSA_NOT_ENOUGH_MEMORY
There was insufficient memory to perform the
operation.
WSAGetServiceClassInfo 207
5.2.3. WSAGetServiceClassInfo
Description WSAGetServiceClassInfo() is used to retrieve all of the class information (schema)
pertaining to a specified service class from a specified name space provider.
INT WSAAPI
WSAGetServiceClassInfo(
IN LPGUID lpProviderId,
IN LPGUID lpServiceClassId,
IN OUT LPDWORD lpdwBufferLength,
OUT LPWSASERVICECLASSINFO lpServiceClassInfo
);
Remarks The service class information retrieved from a particular name space provider may not
necessarily be the complete set of class information that was supplied when the service
class was installed. Individual name space providers are only required to retain service
class information that is applicable to the name spaces that they support. See section
5.1.3.2. Service Class Data Structuresfor more information.
Return Value The return value is 0 if the operation was successful. Otherwise the value
SOCKET_ERROR is returned, and a specific error number may be retrieved by calling
WSAGetLastError().
Errors WSAEACCES The calling routine does not have sufficient privileges
to access the information.
WSA_NOT_ENOUGH_MEMORY
There was insufficient memory to perform the
operation.
208 WSAGetServiceClassNameByClassId
5.2.4. WSAGetServiceClassNameByClassId()
Description This API will return the name of the service associated with the given type. This name is
the generic service name, like FTP, or SNA, and not the name of a specific instance of
that service.
INT WSAAPI
WSAGetServiceClassNameByClassId(
IN LPGUID lpServiceClassId,
OUT LPTSTR lpszServiceClassName,
IN OUT LPDWORD lpdwBufferLength
);
Return Value The return value is 0 if the operation was successful. Otherwise the value
SOCKET_ERROR is returned, and a specific error number may be retrieved by calling
WSAGetLastError().
WSA_NOT_ENOUGH_MEMORY
There was insufficient memory to perform the
operation.
WSAInstallServiceClass 209
5.2.5. WSAInstallServiceClass()
INT WSAAPI
WSAInstallServiceClass(
IN LPWSASERVICECLASSINFO lpServiceClassInfo,
);
See section 5.1.3.2. Service Class Data Structures for a description of pertinent data
structures.
Return Value The return value is 0 if the operation was successful. Otherwise the value
SOCKET_ERROR is returned, and a specific error number may be retrieved by calling
WSAGetLastError().
Errors WSAEACCES The calling routine does not have sufficient privileges
to install the Service.
WSA_NOT_ENOUGH_MEMORY
There was insufficient memory to perform the
operation.
210 WSALookupServiceBegin
5.2.6. WSALookupServiceBegin()
Description WSALookupServiceBegin() is used to initiate a client query that is constrained by the
information contained within a WSAQUERYSET structure. WSALookupServiceBegin()
only returns a handle, which should be used by subsequent calls to
WSALookupServiceNext() to get the actual results.
INT WSAAPI
WSALookupServiceBegin (
IN LPWSAQUERYSET lpqsRestrictions,
IN DWORD dwControlFlags,
OUT LPHANDLE lphLookup
);
Some name service providers may have other means of finding containers. For example,
containers might all be of some well-known type, or of a set of well-known types, and
therefore a query restriction may be created for finding them. No matter what other means
the name service provider has for locating containers, LUP_CONTAINERS and
LUP_NOCONTAINERS take precedence. Hence, if a query restriction is given that
includes containers, specifying LUP_NOCONTAINERS will prevent the container items
from being returned. Similarly, no matter the query restriction, if LUP_CONTAINERS is
given, only containers should be returned. If a name space does not support containers,
and LUP_CONTAINERS is specified, it should simply return WSANO_DATA.
The preferred method of obtaining the containers within another container, is the call:
dwStatus = WSALookupServiceBegin(
lpqsRestrictions,
LUP_CONTAINERS,
lphLookup);
followed by the requisite number of WSALookupServiceNext calls. This will return all
containers contained immediately within the starting context; that is, it is not a deep
query. With this, one can map the address space structure by walking the hierarchy,
perhaps enumerating the content of selected containers. Subsequent uses of
WSALookupServiceBegin use the containers returned from a previous call.
Forming Queries
As mentioned above, a WSAQUERYSET structure is used as an input parameter to
WSALookupBegin() in order to qualify the query. The following table indicates how the
WSAQUERYSET is used to construct a query. When a field is marked as (Optional) a
NULL pointer may be supplied, indicating that the field will not be used as a search
criteria. See section 5.1.3.1. Query-Related Data Structures for additional information.
Important Note:
In most instances, applications interested in only a particular transport protocol should
constrain their query by address family and protocol rather than by name space. This
would allow an application that wishes to locate a TCP/IP service, for example, to have
its query processed by all available name spaces such as the local hosts file, DNS, NIS,
etc.
Return Value The return value is 0 if the operation was successful. Otherwise the value
SOCKET_ERROR is returned, and a specific error number may be retrieved by calling
WSAGetLastError().
Errors
WSAEINVAL One or more parameters were invalid for this provider
or missing.
WSA_NOT_ENOUGH_MEMORY
There was insufficient memory to perform the
operation.
WSALookupServiceEnd 213
5.2.7. WSALookupServiceEnd()
INT WSAAPI
WSALookupServiceEnd (
IN HANDLE hLookup,
);
Return Value The return value is 0 if the operation was successful. Otherwise the value
SOCKET_ERROR is returned, and a specific error number may be retrieved by calling
WSAGetLastError().
WSA_NOT_ENOUGH_MEMORY
There was insufficient memory to perform the
operation.
214 WSALookupServiceNext
5.2.8. WSALookupServiceNext()
INT WSAAPI
WSALookupServiceNext (
IN HANDLE hLookup,
IN DWORD dwControlFlags,
IN OUT LPDWORD lpdwBufferLength,
OUT LPWSAQUERYSET lpqsResults
);
lpqsResults a pointer to a block of memory, which will contain one result set in a
WSAQUERYSET structure on return.
Remarks The dwControlFlags specified in this function and the ones specified at the time of
WSALookupServiceBegin() are treated as “restrictions” for the purpose of combination.
The restrictions are combined between the ones at WSALookupServiceBegin() time and
the ones at WSALookupServiceNext() time. Therefore the flags at
WSALookupServiceNext() can never increase the amount of data returned beyond what
was requested at WSALookupServiceBegin(), although it is NOT an error to specify
more or fewer flags. The flags specified at a given WSALookupServiceNext() apply
only to that call.
Query Results
The following table describes how the query results are represented in the
WSAQUERYSET structure. Refer to section 5.1.3.1. Query-Related Data Structures for
additional information.
Return Value The return value is 0 if the operation was successful. Otherwise the value
SOCKET_ERROR is returned, and a specific error number may be retrieved by calling
WSAGetLastError().
WSA_NOT_ENOUGH_MEMORY
There was insufficient memory to perform the
operation.
WSARemoveServiceClass 217
5.2.9. WSARemoveServiceClass()
INT WSAAPI
WSARemoveServiceClass(
IN LPGUID lpServiceClassId
);
lpServiceClassId Pointer to the GUID for the service class that you wish to remove.
Return Value The return value is 0 if the operation was successful. Otherwise the value
SOCKET_ERROR is returned, and a specific error number may be retrieved by calling
WSAGetLastError().
WSA_NOT_ENOUGH_MEMORY
There was insufficient memory to perform the
operation.
218 WSASetService
4.2.10. WSASetService()
Description WSASetService() is used to register or deregister a service instance within one or more
name spaces. This function may be used to affect a specific name space provider, all
providers associated with a specific name space, or all providers across all name spaces.
INT WSAAPI
WSASetService(
IN LPWSAQUERYSET lpqsRegInfo,
IN WSAESETSERVICEOP essOperation,
IN DWORD dwControlFlags
);
RNRSERVICE_REGISTER register the service. For SAP, this means sending out
a periodic broadcast. This is a NOP for the DNS name space. For
persistent data stores this means updating the address information.
The available values for essOperation and dwControlFlags combine to give meanings as
shown in the following table:
REGISTERED. REGISTERED.
RNRSERVICE_ none Remove all addresses, WSASERVICE_NOT_F
DEREGISTER but do not remove object OUND
from name space.
Object is
DEREGISTERED.
RNRSERVICE_ SERVICE_ Update object. Remove WSASERVICE_NOT_F
DEREGISTER MULTIPLE only addresses that are OUND
specified. Only mark
object as
DEREGISTERED if no
addresses present. Do
not remove from the
name space.
RNRSERVICE_ none Remove object from the WSASERVICE_NOT_F
DELETE name space. OUND
RNRSERVICE_ SERVICE_ Remove only addresses WSASERVICE_NOT_F
DELETE MULTIPLE that are specified. Only OUND
remove object from the
name space if no
addresses remain.
When using SERVICE_MULTIPLE, an application must not let stale addresses remain in
the object. This can happen if the application aborts without issuing a DEREGISTER
request. When a service registers, it should store its addresses. On its next invocation,
the service should explicitly deregister these old stale addresses before registering new
addresses.
Service Properties
The following table describes how service property data is represented in a
WSAQUERYSET structure. Fields labeled as (Optional) may be supplied with a NULL
pointer.
Return Value The return value is 0 if the operation was successful. Otherwise the value
SOCKET_ERROR is returned, and a specific error number may be retrieved by calling
WSAGetLastError().
Errors WSAEACCES The calling routine does not have sufficient privileges
to install the Service.
WSA_NOT_ENOUGH_MEMORY
There was insufficient memory to perform the
operation.
5.2.10. WSAStringToAddress()
INT WSAAPI
WSAStringToAddress(
IN LPTSTR AddressString,
IN INT AddressFamily,
IN LPWSAPROTOCOL_INFO lpProtocolInfo,
OUT LPSOCKADDR lpAddress,
IN OUT LPINT lpAddressLength
);
lpAddressLength The length of the Address buffer. Returns the size of the resultant
SOCKADDR structure. If the supplied buffer is not large enough, the
function fails with a specific error of WSAEFAULT and this parameter
is updated with the required size in bytes.
Return Value The return value is 0 if the operation was successful. Otherwise the value
SOCKET_ERROR is returned, and a specific error number may be retrieved by calling
WSAGetLastError().
WSA_NOT_ENOUGH_MEMORY
There was insufficient memory to perform the
operation.
222 WinSock 1.1 Compatible Name Resolution for TCP/IP
There are also two functions (now implemented in the WinSock 2 DLL) used to convert dotted IPv4
internet address notation to and from string and binary representations, respectively:
• inet_addr()
• inet_ntoa()
All of these functions are specific to IPv4 TCP/IP networks and developers of protocol-independent
applications are discouraged from continuing to utilize these transport-specific functions. However, in order
to retain strict backwards compatibility with WinSock 1.1, all of the above functions continue to be
supported as long as at least one name space provider is present that supports the AF_INET address family
(these functions are not relevant to IP version 6, denoted by AF_INET6).
The WinSock 2 DLL implements these compatibility functions in terms of the new, protocol-independent
name resolution facilities using an appropriate sequence of WSALookupServiceBegin/Next/End()
function calls. The details of how the getXbyY() functions are mapped to name resolution functions are
provided below. Note that the WinSock 2 DLL handles the differences between the asynchronous and
synchronous versions of the getXbyY() functions, so only the implementation of the synchronous
getXbyY() functions are discussed.
5.3.5. gethostbyname()
The WSALookupServiceBegin() query uses SVCID_INET_HOSTADDRBYNAME as the service class
GUID. The host name is supplied in lpszServiceInstanceName. The WinSock 2 DLL specifies
LUP_RETURN_BLOB and the NSP places a hostent struct in the blob (using offsets instead of pointers as
described above). NSPs should honor these other LUP_RETURN_* flags as well:
LUP_RETURN_NAME -> return the h_name field from hostent struct in
lpszServiceInstanceName
LUP_RETURN_ADDR -> return addressing info from hostent in CSADDR_INFO structs, port
information is defaulted to zero. Note that this routine does not resolve host names that consist of
a dotted internet address.
5.3.6. gethostbyaddr()
The WSALookupServiceBegin() query uses SVCID_INET_HOSTNAMEBYADDR as the service class
GUID. The host address is supplied in lpszServiceInstanceName as a dotted internet string (e.g.
"192.9.200.120"). The WinSock 2 DLL specifies LUP_RETURN_BLOB and the NSP places a hostent
struct in the blob (using offsets instead of pointers as described above). NSPs should honor these other
LUP_RETURN_* flags as well:
LUP_RETURN_NAME -> return the h_name field from hostent struct in
lpszServiceInstanceName
LUP_RETURN_ADDR -> return addressing info from hostent in CSADDR_INFO structs, port
information is defaulted to zero
5.3.7. gethostname()
The WSALookupServiceBegin() query uses SVCID_HOSTNAME as the service class GUID. If
lpszServiceInstanceName is NULL or references a NULL string (i.e. ""), the local host is to be resolved.
Otherwise, a lookup on a specified host name shall occur. For the purposes of emulating gethostname() the
WinSock 2 DLL will specify a null pointer for lpszServiceInstanceName, and specify
LUP_RETURN_NAME so that the host name is returned in the lpszServiceInstanceName field. If an
application uses this query and specifies LUP_RETURN_ADDR then the host address will be provided in a
CSADDR_INFO struct. The LUP_RETURN_BLOB action is undefined for this query. Port information
will be defaulted to zero unless the lpszQueryString references a service such as "ftp", in which case the
complete transport address of the indicated service will be supplied.
224 gethostbyaddr
5.4.1. gethostbyaddr()
Description Get host information corresponding to an address.
#include <winsock2.h>
Remarks gethostbyaddr() returns a pointer to the following structure which contains the name(s)
and address which correspond to the given address. All strings are null terminated.
struct hostent {
char FAR * h_name;
char FAR * FAR * h_aliases;
short h_addrtype;
short h_length;
char FAR * FAR * h_addr_list;
};
The macro h_addr is defined to be h_addr_list[0] for compatibility with older software.
The pointer which is returned points to a structure which is allocated by WinSock . The
application must never attempt to modify this structure or to free any of its components.
Furthermore, only one copy of this structure is allocated per thread, and so the application
should copy any information which it needs before issuing any other WinSock API calls.
h_name is the official name of the host. If using the DNS or similar resolution system, it is
the Fully Qualified Domain Name (FQDN) that caused the server to return a reply. If
using a local "hosts" file, it is the first entry after the IP address.
gethostbyaddr 225
Return Value If no error occurs, gethostbyaddr() returns a pointer to the hostent structure described
above. Otherwise it returns a NULL pointer and a specific error number may be retrieved
by calling WSAGetLastError().
5.4.2. gethostbyname()
Description Get host information corresponding to a hostname.
#include <winsock2.h>
The pointer which is returned points to a structure which is allocated by WinSock. The
application must never attempt to modify this structure or to free any of its components.
Furthermore, only one copy of this structure is allocated per thread, and so the application
should copy any information which it needs before issuing any other WinSock API calls.
gethostbyname() does not resolve IP address strings passed to it. Such a request is
treated exactly as if an unknown host name were passed. An application with an IP
address string to resolve should use inet_addr() to convert the string to an IP address,
then gethostbyaddr() to obtain the hostent structure.
Return Value If no error occurs, gethostbyname() returns a pointer to the hostent structure described
above. Otherwise it returns a NULL pointer and a specific error number may be retrieved
by calling WSAGetLastError().
5.4.3. gethostname()
Description Return the standard host name for the local machine.
#include <winsock2.h>
int WSAAPI
gethostname (
OUT char FAR * name,
IN int namelen
);
Remarks This routine returns the name of the local host into the buffer specified by the name
parameter. The host name is returned as a null-terminated string. The form of the host
name is dependent on the WinSock provider--it may be a simple host name, or it may be a
fully qualified domain name. However, it is guaranteed that the name returned will be
successfully parsed by gethostbyname() and WSAAsyncGetHostByName().
Note: If no local host name has been configured gethostname() must succeed and return
a token host name that gethostbyname() or WSAAsyncGetHostByName() can resolve.
Return Value If no error occurs, gethostname() returns 0, otherwise it returns SOCKET_ERROR and a
specific error code may be retrieved by calling WSAGetLastError().
Error Codes WSAEFAULT The name argument is not a valid part of the user
address space, or the buffer size specified by namelen
argument is too small to hold the complete host name.
5.4.4. getprotobyname()
Description Get protocol information corresponding to a protocol name.
#include <winsock2.h>
Remarks getprotobyname() returns a pointer to the following structure which contains the name(s)
and protocol number which correspond to the given protocol name. All strings are null
terminated.
struct protoent {
char FAR * p_name;
char FAR * FAR * p_aliases;
short p_proto;
};
The pointer which is returned points to a structure which is allocated by the WinSock
library. The application must never attempt to modify this structure or to free any of its
components. Furthermore only one copy of this structure is allocated per thread, and so
the application should copy any information which it needs before issuing any other
WinSock API calls.
Return Value If no error occurs, getprotobyname() returns a pointer to the protoent structure described
above. Otherwise it returns a NULL pointer and a specific error number may be retrieved
by calling WSAGetLastError().
5.4.5. getprotobynumber()
Description Get protocol information corresponding to a protocol number.
#include <winsock2.h>
The pointer which is returned points to a structure which is allocated by WinSock. The
application must never attempt to modify this structure or to free any of its components.
Furthermore, only one copy of this structure is allocated per thread, and so the application
should copy any information which it needs before issuing any other WinSock API calls.
Return Value If no error occurs, getprotobynumber() returns a pointer to the protoent structure
described above. Otherwise it returns a NULL pointer and a specific error number may
be retrieved by calling WSAGetLastError().
5.4.6. getservbyname()
Description Get service information corresponding to a service name and protocol.
#include <winsock2.h>
Remarks getservbyname() returns a pointer to the following structure which contains the name(s)
and service number which correspond to the given service name. All strings are null
terminated.
struct servent {
char FAR * s_name;
char FAR * FAR * s_aliases;
short s_port;
char FAR * s_proto;
};
The pointer which is returned points to a structure which is allocated by the WinSock
library. The application must never attempt to modify this structure or to free any of its
components. Furthermore only one copy of this structure is allocated per thread, and so
the application should copy any information which it needs before issuing any other
WinSock API calls.
Return Value If no error occurs, getservbyname() returns a pointer to the servent structure described
above. Otherwise it returns a NULL pointer and a specific error number may be retrieved
by calling WSAGetLastError().
5.4.7. getservbyport()
Description Get service information corresponding to a port and protocol.
#include <winsock2.h>
The pointer which is returned points to a structure which is allocated by WinSock. The
application must never attempt to modify this structure or to free any of its components.
Furthermore, only one copy of this structure is allocated per thread, and so the application
should copy any information which it needs before issuing any other WinSock API calls.
Return Value If no error occurs, getservbyport() returns a pointer to the servent structure described
above. Otherwise it returns a NULL pointer and a specific error number may be retrieved
by calling WSAGetLastError().
5.4.8. inet_addr()
Description Convert a string containing an (IPv4) Internet Protocol dotted address into an in_addr.
#include <winsock2.h>
Remarks This function interprets the character string specified by the cp parameter. This string
represents a numeric Internet address expressed in the Internet standard ".'' notation. The
value returned is a number suitable for use as an Internet address. All Internet addresses
are returned in IP’s network order (bytes ordered from left to right).
Internet Addresses
Values specified using the ".'' notation take one of the following forms:
When four parts are specified, each is interpreted as a byte of data and assigned, from left
to right, to the four bytes of an Internet address. Note that when an Internet address is
viewed as a 32-bit integer quantity on the Intel architecture, the bytes referred to above
appear as "d.c.b.a''. That is, the bytes on an Intel processor are ordered from right to left.
Note: The following notations are only used by Berkeley, and nowhere else on the
Internet. In the interests of compatibility with their software, they are supported as
specified.
When a three part address is specified, the last part is interpreted as a 16-bit quantity and
placed in the right most two bytes of the network address. This makes the three part
address format convenient for specifying Class B network addresses as "128.net.host''.
When a two part address is specified, the last part is interpreted as a 24-bit quantity and
placed in the right most three bytes of the network address. This makes the two part
address format convenient for specifying Class A network addresses as "net.host''.
When only one part is given, the value is stored directly in the network address without
any byte rearrangement.
Return Value If no error occurs, inet_addr() returns an unsigned long containing a suitable binary
representation of the Internet address given. If the passed-in string does not contain a
legitimate Internet address, for example if a portion of an "a.b.c.d" address exceeds 255,
inet_addr() returns the value INADDR_NONE.
5.4.9. inet_ntoa()
Description Convert an (IPv4) Internet network address into a string in dotted format.
#include <winsock2.h>
Remarks This function takes an Internet address structure specified by the in parameter. It returns
an ASCII string representing the address in ".'' notation as "a.b.c.d''. Note that the string
returned by inet_ntoa() resides in memory which is allocated by WinSock . The
application should not make any assumptions about the way in which the memory is
allocated. The data is guaranteed to be valid until the next WinSock API call within the
same thread, but no longer.
Return Value If no error occurs, inet_ntoa() returns a char pointer to a static buffer containing the text
address in standard ".'' notation. Otherwise, it returns NULL. The data should be copied
before another WinSock call is made.
5.4.10. WSAAsyncGetHostByAddr()
Description Get host information corresponding to an address - asynchronous version.
#include <winsock2.h>
HANDLE WSAAPI
WSAAsyncGetHostByAddr (
IN HWND hWnd,
IN unsigned int wMsg,
IN const char FAR * addr,
IN int len,
IN int type,
OUT char FAR* buf,
IN int buflen
);
hWnd The handle of the window which should receive a message when the
asynchronous request completes.
addr A pointer to the network address for the host. Host addresses are stored
in network byte order.
buf A pointer to the data area to receive the hostent data. Note that this
must be larger than the size of a hostent structure. This is because the
data area supplied is used by WinSock to contain not only a hostent
structure but any and all of the data which is referenced by members of
the hostent structure. It is recommended that you supply a buffer of
MAXGETHOSTSTRUCT bytes.
Remarks This function is an asynchronous version of gethostbyaddr(), and is used to retrieve host
name and address information corresponding to a network address. WinSock initiates the
operation and returns to the caller immediately, passing back an opaque "asynchronous
task handle" which the application may use to identify the operation. When the operation
is completed, the results (if any) are copied into the buffer provided by the caller and a
message is sent to the application's window.
When the asynchronous operation is complete the application's window hWnd receives
message wMsg. The wParam argument contains the asynchronous task handle as
returned by the original function call. The high 16 bits of lParam contain any error code.
The error code may be any error as defined in winsock2.h. An error code of zero
indicates successful completion of the asynchronous operation. On successful
completion, the buffer supplied to the original function call contains a hostent structure.
To access the elements of this structure, the original buffer address should be cast to a
hostent structure pointer and accessed as appropriate.
WSAAsyncGetHostByAddr 239
Note that if the error code is WSAENOBUFS, it indicates that the size of the buffer
specified by buflen in the original call was too small to contain all the resultant
information. In this case, the low 16 bits of lParam contain the size of buffer required to
supply ALL the requisite information. If the application decides that the partial data is
inadequate, it may reissue the WSAAsyncGetHostByAddr() function call with a buffer
large enough to receive all the desired information (i.e. no smaller than the low 16 bits
of lParam).
The error code and buffer length should be extracted from the lParam using the macros
WSAGETASYNCERROR and WSAGETASYNCBUFLEN, defined in winsock2.h as:
The use of these macros will maximize the portability of the source code for the
application.
Return Value The return value specifies whether or not the asynchronous operation was successfully
initiated. Note that it does not imply success or failure of the operation itself.
Comments The buffer supplied to this function is used by WinSock to construct a hostent structure
together with the contents of data areas referenced by members of the same hostent
structure. To avoid the WSAENOBUFS error noted above, the application should
provide a buffer of at least MAXGETHOSTSTRUCT bytes (as defined in winsock2.h).
Error Codes The following error codes may be set when an application window receives a message.
As described above, they may be extracted from the lParam in the reply message using
the WSAGETASYNCERROR macro.
The following errors may occur at the time of the function call, and indicate that the
asynchronous operation could not be initiated.
5.4.11. WSAAsyncGetHostByName()
Description Get host information corresponding to a hostname - asynchronous version.
#include <winsock2.h>
HANDLE WSAAPI
WSAAsyncGetHostByName (
IN HWND hWnd,
IN unsigned int wMsg,
IN const char FAR * name,
OUT char FAR * buf,
IN int buflen
);
hWnd The handle of the window which should receive a message when the
asynchronous request completes.
buf A pointer to the data area to receive the hostent data. Note that this
must be larger than the size of a hostent structure. This is because the
data area supplied is used by WinSock to contain not only a hostent
structure but any and all of the data which is referenced by members of
the hostent structure. It is recommended that you supply a buffer of
MAXGETHOSTSTRUCT bytes.
Remarks This function is an asynchronous version of gethostbyname(), and is used to retrieve host
name and address information corresponding to a hostname. WinSock initiates the
operation and returns to the caller immediately, passing back an opaque "asynchronous
task handle" which the application may use to identify the operation. When the operation
is completed, the results (if any) are copied into the buffer provided by the caller and a
message is sent to the application's window.
When the asynchronous operation is complete the application's window hWnd receives
message wMsg. The wParam argument contains the asynchronous task handle as
returned by the original function call. The high 16 bits of lParam contain any error code.
The error code may be any error as defined in winsock2.h. An error code of zero
indicates successful completion of the asynchronous operation. On successful
completion, the buffer supplied to the original function call contains a hostent structure.
To access the elements of this structure, the original buffer address should be cast to a
hostent structure pointer and accessed as appropriate.
Note that if the error code is WSAENOBUFS, it indicates that the size of the buffer
specified by buflen in the original call was too small to contain all the resultant
information. In this case, the low 16 bits of lParam contain the size of buffer required to
supply ALL the requisite information. If the application decides that the partial data is
inadequate, it may reissue the WSAAsyncGetHostByName() function call with a buffer
large enough to receive all the desired information (i.e. no smaller than the low 16 bits of
lParam).
242 WSAAsyncGetHostByName
The error code and buffer length should be extracted from the lParam using the macros
WSAGETASYNCERROR and WSAGETASYNCBUFLEN, defined in winsock2.h as:
The use of these macros will maximize the portability of the source code for the
application.
Return Value The return value specifies whether or not the asynchronous operation was successfully
initiated. Note that it does not imply success or failure of the operation itself.
Comments The buffer supplied to this function is used by WinSock to construct a hostent structure
together with the contents of data areas referenced by members of the same hostent
structure. To avoid the WSAENOBUFS error noted above, the application should
provide a buffer of at least MAXGETHOSTSTRUCT bytes (as defined in winsock2.h).
Error Codes The following error codes may be set when an application window receives a message.
As described above, they may be extracted from the lParam in the reply message using
the WSAGETASYNCERROR macro.
The following errors may occur at the time of the function call, and indicate that the
asynchronous operation could not be initiated.
WSAAsyncGetHostByName 243
5.4.12. WSAAsyncGetProtoByName()
Description Get protocol information corresponding to a protocol name - asynchronous version.
#include <winsock2.h>
HANDLE WSAAPI
WSAAsyncGetProtoByName (
IN HWND hWnd,
IN unsigned int wMsg,
IN const char FAR * name,
OUT char FAR * buf,
IN int buflen
);
hWnd The handle of the window which should receive a message when the
asynchronous request completes.
buf A pointer to the data area to receive the protoent data. Note that this
must be larger than the size of a protoent structure. This is because the
data area supplied is used by WinSock to contain not only a protoent
structure but any and all of the data which is referenced by members of
the protoent structure. It is recommended that you supply a buffer of
MAXGETHOSTSTRUCT bytes.
When the asynchronous operation is complete the application's window hWnd receives
message wMsg. The wParam argument contains the asynchronous task handle as
returned by the original function call. The high 16 bits of lParam contain any error code.
The error code may be any error as defined in winsock2.h. An error code of zero
indicates successful completion of the asynchronous operation. On successful
completion, the buffer supplied to the original function call contains a protoent structure.
To access the elements of this structure, the original buffer address should be cast to a
protoent structure pointer and accessed as appropriate.
Note that if the error code is WSAENOBUFS, it indicates that the size of the buffer
specified by buflen in the original call was too small to contain all the resultant
information. In this case, the low 16 bits of lParam contain the size of buffer required to
supply ALL the requisite information. If the application decides that the partial data is
inadequate, it may reissue the WSAAsyncGetProtoByName() function call with a buffer
large enough to receive all the desired information (i.e. no smaller than the low 16 bits
of lParam).
WSAAsyncGetProtoByName 245
The error code and buffer length should be extracted from the lParam using the macros
WSAGETASYNCERROR and WSAGETASYNCBUFLEN, defined in winsock2.h as:
The use of these macros will maximize the portability of the source code for the
application.
Return Value The return value specifies whether or not the asynchronous operation was successfully
initiated. Note that it does not imply success or failure of the operation itself.
Comments The buffer supplied to this function is used by WinSock to construct a protoent structure
together with the contents of data areas referenced by members of the same protoent
structure. To avoid the WSAENOBUFS error noted above, the application should
provide a buffer of at least MAXGETHOSTSTRUCT bytes (as defined in winsock2.h).
Error Codes The following error codes may be set when an application window receives a message.
As described above, they may be extracted from the lParam in the reply message using
the WSAGETASYNCERROR macro.
The following errors may occur at the time of the function call, and indicate that the
asynchronous operation could not be initiated.
246 WSAAsyncGetProtoByName
5.4.13. WSAAsyncGetProtoByNumber()
Description Get protocol information corresponding to a protocol number - asynchronous version.
#include <winsock2.h>
HANDLE WSAAPI
WSAAsyncGetProtoByNumber (
IN HWND hWnd,
IN unsigned int wMsg,
IN int number,
OUT char FAR * buf,
IN int buflen
);
hWnd The handle of the window which should receive a message when the
asynchronous request completes.
buf A pointer to the data area to receive the protoent data. Note that this
must be larger than the size of a protoent structure. This is because the
data area supplied is used by WinSock to contain not only a protoent
structure but any and all of the data which is referenced by members of
the protoent structure. It is recommended that you supply a buffer of
MAXGETHOSTSTRUCT bytes.
When the asynchronous operation is complete the application's window hWnd receives
message wMsg. The wParam argument contains the asynchronous task handle as
returned by the original function call. The high 16 bits of lParam contain any error code.
The error code may be any error as defined in winsock2.h. An error code of zero
indicates successful completion of the asynchronous operation. On successful
completion, the buffer supplied to the original function call contains a protoent structure.
To access the elements of this structure, the original buffer address should be cast to a
protoent structure pointer and accessed as appropriate.
Note that if the error code is WSAENOBUFS, it indicates that the size of the buffer
specified by buflen in the original call was too small to contain all the resultant
information. In this case, the low 16 bits of lParam contain the size of buffer required to
supply ALL the requisite information. If the application decides that the partial data is
inadequate, it may reissue the WSAAsyncGetProtoByNumber() function call with a
buffer large enough to receive all the desired information (i.e. no smaller than the low 16
bits of lParam).
248 WSAAsyncGetProtoByNumber
The error code and buffer length should be extracted from the lParam using the macros
WSAGETASYNCERROR and WSAGETASYNCBUFLEN, defined in winsock2.h as:
The use of these macros will maximize the portability of the source code for the
application.
Return Value The return value specifies whether or not the asynchronous operation was successfully
initiated. Note that it does not imply success or failure of the operation itself.
Comments The buffer supplied to this function is used by WinSock to construct a protoent structure
together with the contents of data areas referenced by members of the same protoent
structure. To avoid the WSAENOBUFS error noted above, the application should
provide a buffer of at least MAXGETHOSTSTRUCT bytes (as defined in winsock2.h).
Error Codes The following error codes may be set when an application window receives a message.
As described above, they may be extracted from the lParam in the reply message using
the WSAGETASYNCERROR macro.
The following errors may occur at the time of the function call, and indicate that the
asynchronous operation could not be initiated.
5.4.14. WSAAsyncGetServByName()
Description Get service information corresponding to a service name and port - asynchronous version.
#include <winsock2.h>
HANDLE WSAAPI
WSAAsyncGetServByName (
IN HWND hWnd,
IN unsigned int wMsg,
IN const char FAR * name,
IN const char FAR * proto,
OUT char FAR * buf,
IN int buflen
);
hWnd The handle of the window which should receive a message when the
asynchronous request completes.
buf A pointer to the data area to receive the servent data. Note that this
must be larger than the size of a servent structure. This is because the
data area supplied is used by WinSock to contain not only a servent
structure but any and all of the data which is referenced by members of
the servent structure. It is recommended that you supply a buffer of
MAXGETHOSTSTRUCT bytes.
When the asynchronous operation is complete the application's window hWnd receives
message wMsg. The wParam argument contains the asynchronous task handle as
returned by the original function call. The high 16 bits of lParam contain any error code.
The error code may be any error as defined in winsock2.h. An error code of zero
indicates successful completion of the asynchronous operation. On successful
completion, the buffer supplied to the original function call contains a servent structure.
To access the elements of this structure, the original buffer address should be cast to a
servent structure pointer and accessed as appropriate.
WSAAsyncGetServByName 251
Note that if the error code is WSAENOBUFS, it indicates that the size of the buffer
specified by buflen in the original call was too small to contain all the resultant
information. In this case, the low 16 bits of lParam contain the size of buffer required to
supply ALL the requisite information. If the application decides that the partial data is
inadequate, it may reissue the WSAAsyncGetServByName() function call with a buffer
large enough to receive all the desired information (i.e. no smaller than the low 16 bits of
lParam).
The error code and buffer length should be extracted from the lParam using the macros
WSAGETASYNCERROR and WSAGETASYNCBUFLEN, defined in winsock2.h as:
The use of these macros will maximize the portability of the source code for the
application.
Return Value The return value specifies whether or not the asynchronous operation was successfully
initiated. Note that it does not imply success or failure of the operation itself.
Comments The buffer supplied to this function is used by WinSock to construct a servent structure
together with the contents of data areas referenced by members of the same servent
structure. To avoid the WSAENOBUFS error noted above, the application should
provide a buffer of at least MAXGETHOSTSTRUCT bytes (as defined in winsock2.h).
Error Codes The following error codes may be set when an application window receives a message.
As described above, they may be extracted from the lParam in the reply message using
the WSAGETASYNCERROR macro.
The following errors may occur at the time of the function call, and indicate that the
asynchronous operation could not be initiated.
5.4.15. WSAAsyncGetServByPort()
Description Get service information corresponding to a port and protocol - asynchronous version.
#include <winsock2.h>
HANDLE WSAAPI
WSAAsyncGetServByPort (
IN HWND hWnd,
IN unsigned int wMsg,
IN int port,
IN const char FAR * proto,
OUT char FAR * buf,
IN int buflen
);
hWnd The handle of the window which should receive a message when the
asynchronous request completes.
buf A pointer to the data area to receive the servent data. Note that this
must be larger than the size of a servent structure. This is because the
data area supplied is used by WinSock to contain not only a servent
structure but any and all of the data which is referenced by members of
the servent structure. It is recommended that you supply a buffer of
MAXGETHOSTSTRUCT bytes.
When the asynchronous operation is complete the application's window hWnd receives
message wMsg. The wParam argument contains the asynchronous task handle as
returned by the original function call. The high 16 bits of lParam contain any error code.
The error code may be any error as defined in winsock2.h. An error code of zero
indicates successful completion of the asynchronous operation. On successful
completion, the buffer supplied to the original function call contains a servent structure.
To access the elements of this structure, the original buffer address should be cast to a
servent structure pointer and accessed as appropriate.
254 WSAAsyncGetServByPort
Note that if the error code is WSAENOBUFS, it indicates that the size of the buffer
specified by buflen in the original call was too small to contain all the resultant
information. In this case, the low 16 bits of lParam contain the size of buffer required to
supply ALL the requisite information. If the application decides that the partial data is
inadequate, it may reissue the WSAAsyncGetServByPort() function call with a buffer
large enough to receive all the desired information (i.e. no smaller than the low 16 bits of
lParam).
The error code and buffer length should be extracted from the lParam using the macros
WSAGETASYNCERROR and WSAGETASYNCBUFLEN, defined in winsock2.h as:
The use of these macros will maximize the portability of the source code for the
application.
Return Value The return value specifies whether or not the asynchronous operation was successfully
initiated. Note that it does not imply success or failure of the operation itself.
Comments The buffer supplied to this function is used by WinSock to construct a servent structure
together with the contents of data areas referenced by members of the same servent
structure. To avoid the WSAENOBUFS error noted above, the application should
provide a buffer of at least MAXGETHOSTSTRUCT bytes (as defined in winsock2.h).
Error Codes The following error codes may be set when an application window receives a message.
As described above, they may be extracted from the lParam in the reply message using
the WSAGETASYNCERROR macro.
The following errors may occur at the time of the function call, and indicate that the
asynchronous operation could not be initiated.
5.4.16. WSACancelAsyncRequest()
Description Cancel an incomplete asynchronous operation.
#include <winsock2.h>
int WSAAPI
WSACancelAsyncRequest (
IN HANDLE hAsyncTaskHandle
);
Return Value The value returned by WSACancelAsyncRequest() is 0 if the operation was successfully
canceled. Otherwise the value SOCKET_ERROR is returned, and a specific error
number may be retrieved by calling WSAGetLastError().
Note It is unclear whether the application can usefully distinguish between WSAEINVAL and
WSAEALREADY, since in both cases the error indicates that there is no asynchronous
operation in progress with the indicated handle. [Trivial exception: 0 is always an invalid
asynchronous task handle.] The WinSock specification does not prescribe how a
conformant WinSock provider should distinguish between the two cases. For maximum
portability, a WinSock application should treat the two errors as equivalent.
The first set of definitions is present to resolve contentions between standard C error codes which may be
defined inconsistently between various C compilers.
The second set of definitions provides WinSock versions of regular Berkeley Sockets error codes.
The fourth set of errors are returned by WinSock getXbyY() and WSAAsyncGetXByY() functions, and
correspond to the errors which in Berkeley software would be returned in the h_errno variable. They
correspond to various failures which may be returned by the Domain Name Service. If the WinSock
provider does not use the DNS, it will use the most appropriate code. In general, a WinSock application
should interpret WSAHOST_NOT_FOUND and WSANO_DATA as indicating that the key (name,
address, etc.) was not found, while WSATRY_AGAIN and WSANO_RECOVERY suggest that the name
service itself is non-operational.
The error numbers are derived from the Winsock2.h header file listed in section A.2.2 , and are based on
the fact that WinSock error numbers are computed by adding 10000 to the "normal" Berkeley error number.
Note that this table does not include all of the error codes defined in Winsock2.h. This is because it
includes only errors which might reasonably be returned by a WinSock implementation: Winsock2.h, on
the other hand, includes a full set of BSD definitions to ensure compatibility with ported software.
An address incompatible with the requested protocol was used. All sockets are created with an
associated "address family" (i.e. AF_INET for Internet Protocols) and a generic protocol type (i.e.
SOCK_STREAM). This error will be returned if an incorrect protocol is explicitly requested in the
socket() call, or if an address of the wrong family is used for a socket, e.g. in sendto().
Some invalid argument was supplied (for example, specifying an invalid level to the setsockopt()
function). In some instances, it also refers to the current state of the socket - for instance, calling
accept() on a socket that is not listen()ing.
WSA_IO_INCOMPLETE (OS dependent) Overlapped I/O event object not in signaled state.
The application has tried to determine the status of an overlapped operation which is not yet
completed. Applications that use WSAGetOverlappedResult() (with the fWait flag set to false)
in a polling mode to determine when an overlapped operation has completed will get this error
code until the operation is complete.
WSA_IO_PENDING (OS dependent) Overlapped operations will complete later.
The application has initiated an overlapped operation which cannot be completed immediately. A
completion indication will be given at a later time when the operation has been completed.
• • that they are not trying to use more than one WinSock implementation simultaneously. If
there is more than one WINSOCK DLL on your system, be sure the first one in the path is
appropriate for the network subsystem currently loaded.
• the WinSock implementation documentation to be sure all necessary components are
currently installed and configured correctly.
#ifndef _WinsockAPI_
#include <Winsock2.h>
#endif
The file Winsock2.h contains all of the type and structure definitions, constants, macros, and function
prototypes used by the WinSock specification. An application writer may choose to ignore the
compatibility headers and include Winsock2.h in each source file.
WinSock2.h 267
A WinSock service provider vendor MUST NOT make any modifications to this header file which could
impact binary compatibility of WinSock applications. The constant values, function parameters and return
codes, and the like must remain consistent across all WinSock service provider vendors.
New versions of Winsock2.h will appear periodically as new identifiers are allocated by the WinSock
Identifier Clearinghouse. The clearinghouse can be reached via the world wide web at
http://www.stardust.com/wsresource/winsock2/ws2ident.html
Developers are urged to stay current with successive revisions of Winsock2.h as they are made available by
the clearinghouse.
The Winsock2.h header file now supports UNICODE, and thus contains both A and W declarations for all
applicable functions and structures. In addition, both function prototypes and function typedefs are
supplied. As a result, the Winsock2.h header file has become quite lengthy (in excess of 40 pages when
printed). Because it has grown so large and is subject to frequent updates, Winsock2.h is no longer being
copied verbatim into this specification document.
268 Appendix B: Windows Sockets Introduction
In the control plane there are two distinct types of session establishment: rooted and non-rooted. In the
case of rooted control, there exists a special participant, called c_root, that is different from the rest of the
members of this multipoint session, each of which is called a c_leaf. The c_root must remain present for the
whole duration of the multipoint session, as the session will be broken up in the absence of the c_root. The
c_root usually initiates the multipoint session by setting up the connection to a c_leaf, or a number of
c_leafs. The c_root may add more c_leafs, or (in some cases) a c_leaf can join the c_root at a later time.
Examples of the rooted control plane can be found in ATM and ST-II.
For a non-rooted control plane, all the members belonging to a multipoint session are leaves, i.e., no special
participant acting as a c_root exists. Each c_leaf needs to add itself to a pre-existing multipoint session that
either is always available (as in the case of an IP multicast address), or has been set up through some out-
of-band mechanism which is outside the scope of the WinSock specification. Another way to look at this is
that a c_root still exists, but can be considered to be in the network cloud as opposed to one of the
participants. Because a control root still exists, a non-rooted control plane could also be considered to be
implicitly rooted. Examples for this kind of implicitly rooted multipoint schemes are: a teleconferencing
bridge, the IP multicast system, a Multipoint Control Unit (MCU) in a H.320 video conference, etc.
In the data plane, there are two types of data transfer styles: rooted and non-rooted. In a rooted data plane,
a special participant called d_root exists. Data transfer only occurs between the d_root and the rest of the
members of this multipoint session, each of which is referred to as a d_leaf. The traffic could be uni-
directional, or bi-directional. The data sent out from the d_root will be duplicated (if required) and
delivered to every d_leaf, while the data from d_leafs will only go to the d_root. In the case of a rooted
data plane, there is no traffic allowed among d_leafs. An example of a protocol that is rooted in the data
plane is ST-II.
In a non-rooted data plane, all the participants are equal in the sense that any data they send will be
delivered to all the other participants in the same multipoint session. Likewise each d_leaf node will be
able to receive data from all other d_leafs, and in some cases, from other nodes which are not participating
in the multipoint session as well. No special d_root node exists. IP-multicast is non-rooted in the data
plane.
Note that the question of where data unit duplication occurs, or whether a shared single tree or multiple
shortest-path trees are used for multipoint distribution are protocol issues, and are irrelevant to the interface
the application would use to perform multipoint communications. Therefore these issues are not addressed
either in this appendix or by the WinSock interface.
270 Appendix B: Multipoint and Multicast
The following table depicts the taxonomy described above and indicates how existing schemes fit into each
of the categories. Note that there does not appear to be any existing schemes that employ a non-rooted
control plane along with a rooted data plane.
The paragraphs which follow describe these interface elements in more detail.
B.3.5. WSAJoinLeaf()
The function WSAJoinLeaf() is used to join a leaf node into the multipoint session. The function prototype
is as follows:
SOCKET WSAAPI WSAJoinLeaf ( SOCKET s, const struct sockaddr FAR * name, int
namelen, LPWSABUF lpCallerData, LPWSABUF lpCalleeData, LPQOS lpSQOS,
LPQOS lpGQOS, DWORD dwFlags );
In rooted control plane schemes, new leaf nodes are added to a multipoint session in one or both of two
different ways. In the first method, the root uses WSAJoinLeaf() to initiate a connection with a leaf node
and invite it to become a participant. On the leaf node, the peer application must have created a c_leaf
socket and used listen() to set it into listen mode. The leaf node will receive an FD_ACCEPT indication
when invited to join the session, and signals its willingness to join by calling WSAAccept(). The root
application will receive an FD_CONNECT indication when the join operation has been completed.
In the second method, the roles are essentially reversed. The root application creates a c_root socket and
sets it into listen mode. A leaf node wishing to join the session creates a c_leaf socket and uses
WSAJoinLeaf() to initiate the connection and request admittance. The root application receives
FD_ACCEPT when an incoming admittance request arrives, and admits the leaf node by calling
WSAAccept(). The leaf node receives FD_CONNECT when it has been admitted.
272 Appendix B: Multipoint and Multicast
In a non-rooted control plane, where all nodes are c_leaf’s, the WSAJoinLeaf() is used to initiate the
inclusion of a node into an existing multipoint session. An FD_CONNECT indication is provided when the
join has been completed and the returned socket descriptor is useable in the multipoint session. In the case
of IP multicast, this would correspond to the IP_ADD_MEMBERSHIP socket option. 4
There are, therefore, three instances where an application would use WSAJoinLeaf():
1. Acting as a multipoint root and inviting a new leaf to join the session
2. Acting as a leaf making an admittance request to a rooted multipoint session
3. Acting as a leaf seeking admittance to a non-rooted multipoint session (e.g. IP multicast)
The socket descriptor returned by WSAJoinLeaf() is different depending on whether the input socket
descriptor, s, is a c_root or a c_leaf. When used with a c_root socket, the name parameter designates a
particular leaf node to be added and the returned socket descriptor is a c_leaf socket corresponding to the
newly added leaf node. It is not intended to be used for exchange of multipoint data, but rather is used to
receive FD_XXX indications (e.g. FD_CLOSE) for the connection that exists to the particular c_leaf.
Some multipoint implementations may also allow this socket to be used for “side chats” between the root
and an individual leaf node. An FD_CLOSE indication will be received for this socket if the corresponding
leaf node calls closesocket() to drop out of the multipoint session. Symmetrically, invoking closesocket()
on the c_leaf socket returned from WSAJoinLeaf() will cause the socket in the corresponding leaf node to
get FD_CLOSE notification.
When WSAJoinLeaf() is invoked with a c_leaf socket, the name parameter contains the address of the root
application (for a rooted control scheme) or an existing multipoint session (non-rooted control scheme), and
the returned socket descriptor is the same as the input socket descriptor. In a rooted control scheme, the
root application would put its c_root socket in the listening mode by calling listen(). The standard
FD_ACCEPT notification will be delivered when the leaf node requests to join itself to the multipoint
session. The root application uses the usual accept()/WSAAccept() functions to admit the new leaf node.
The value returned from either accept() or WSAAccept() is also a c_leaf socket descriptor just like those
returned from WSAJoinLeaf(). To accommodate multipoint schemes that allow both root-initiated and
leaf-initiated joins, it is acceptable for a c_root socket that is already in listening mode to be used as in input
to WSAJoinLeaf().
4
Readers familiar with IP multicast’s use of the connectionless UDP protocol may be concerned by the
connection-oriented semantics presented here. In particular the notion of using WSAJoinLeaf() on a UDP
socket and waiting for an FD_CONNECT indication may be troubling. There is, however, ample precedent
for applying connection-oriented semantics to connectionless protocols. It is allowed and sometime useful,
for example, to invoke the standard connect() function on a UDP socket. The general result of applying
connection-oriented semantics to connectionless sockets is a restriction in how such sockets may be used,
and such is the case here as well. A UDP socket used in WSAJoinLeaf() will have certain restrictions, and
waiting for an FD_CONNECT indication (which in this case simply indicates that the corresponding IGMP
message has been sent) is one such limitation.
Appendix B: Multipoint and Multicast 273
A multipoint root application is generally responsible for the orderly dismantling of a multipoint session.
Such an application may use shutdown() or closesocket() on a c_root socket to cause all of the associated
c_leaf sockets, including those returned from WSAJoinLeaf() and their corresponding c_leaf sockets in the
remote leaf nodes, to get FD_CLOSE notification.
There is no semantic differences between a c_leaf socket and a regular socket in the control plane, except
that the c_leaf socket can be used in WSAJoinLeaf(), and the use of c_leaf socket in listen() indicates that
only multipoint connection requests should be accepted.
In the data plane, the semantic differences between the d_root socket and a regular point-to-point socket are
(1) the data sent on the d_root socket will be delivered to all the leaves in the same multipoint
session;
(2) the data received on the d_root socket may be from any of the leaves.
The d_leaf socket in the rooted data plane has no semantic difference from the regular socket, however, in
the non-rooted data plane, the data sent on the d_leaf socket will go to all the other leaf nodes, and the data
received could be from any other leaf nodes. As mentioned earlier, the information about whether the
d_leaf socket is in a rooted or non-rooted data plane is contained in the corresponding
WSAPROTOCOL_INFO structure for the socket.
B.6.1. IP multicast
IP multicast falls into the category of non-rooted data plane and non-rooted control plane. All applications
play a leaf role. Currently most IP multicast implementations use a set of socket options proposed by Steve
Deering to the IETF. Five operations are made thus available:
• IP_MULTICAST_TTL - set time to live, controls scope of multicast session
• IP_MULTICAST_IF - determine interface to be used for multicasting
• IP_ADD_MEMBERSHIP - join a specified multicast session
• IP_DROP_MEMBERSHIP - drop out of a multicast session
• IP_MULTICAST_LOOP - control loopback of multicast traffic
Setting the time-to-live for an IP multicast socket maps directly to using the SIO_MULTICAST_SCOPE
command code for WSAIoctl(). The method for determining the IP interface to be used for multicasting is
via a TCP/IP-specific socket option as described in the WinSock 2 Protocol Specific Annex.
The remaining three operations are covered well with the WinSock 2 semantics described here. The
application would open sockets with c_leaf/d_leaf flags in WSASocket(). It would use WSAJoinLeaf() to
274 Appendix B: Multipoint and Multicast
add itself to a multicast group on the default interface designated for multicast operations. If the flag in
WSAJoinLeaf() indicates that this socket is only a sender, then the join operation is essentially a no-op and
no IGMP messages need to be sent. Otherwise, an IGMP packet is sent out to the router to indicate
interests in receiving packets sent to the specified multicast address. Since the application created special
c_leaf/d_leaf sockets used only for performing multicast, the standard closesocket() function would be used
to drop out of the multicast session. The SIO_MULTIPOINT_LOOP command code for WSAIoctl()
provides a generic control mechanism for determining whether data sent on a d_leaf socket in a non-rooted
multipoint scheme will be also received on the same socket.
-----------------------------
The Windows Sockets Lame List
(or What's Weak This Week)
-----------------------------
brought to you by The Windows Sockets Vendor Community
Reason: The WinSock 1.1 spec does not define an error for connect()
when a non-blocking connection is pending, so the error value
returned may vary.
Alternative: Ideally, you can use a separate socket for urgent data,
although in reality it is inescapable sometimes. Some protocols
require it (see item 7), in which case you need to minimize your
dependence, or beef up your technical support staff to handle user
calls.
Alternative: Don’t use peek reads. Always read data into your application
buffers, and examine the data there.
13. Passing a longer buffer length than the actual buffer size since you
know you won’t receive more than the actual buffer size. Universally lame.
Reason: Error values are your friends! When a function fails, the
error value returned by WSAGetLastError() or included in an asyn-
chronous message can tell you *why* it failed. Based on the
function that failed, and the socket state, you can often infer
what happened, why, and what to do about it.
21. 16-bit DLLs that call WSACleanup() from their WEP. Inconceivably
lame.
Reason: Couple one-byte sends with Nagle disabled, and you have
at best a 40:1 overhead-to-data ratio. Can you say wasted
bandwidth? I thought you could.
Then after select() returns with the number of sockets that have
done something, you need to go through all the fdsets and all
the sockets using the macros to find the event that occurred,
and even then the (lack of) resolution is such you need to
infer the event from the current socket state.
27. Assuming that a UDP datagram of any length may be sent. Criminally lame.
Reason: If you can’t figure out the reason, it’s time to hang up
your keyboard.
30. Expecting errors when UDP datagrams are dropped by the sender,
receiver, or any router along the way. Seeping lameness from every
crack and crevice.
Reason: UDP is unreliable. TCP/IP stacks don’t have to tell you when
they throw your datagrams away (a sender or receiver may do this
when they don’t have buffer space available, and a receiver will do it
if they cannot reassemble a large fragmented datagram.
Comer, D. [1991], Internetworking with TCP/IP Volume I: Principles, Protocols, and Architecture,
Prentice Hall, Englewood Cliffs, New Jersey.
Comer, D. and Stevens, D. [1991], Internetworking with TCP/IP Volume II: Design, Implementation, and
Internals, Prentice Hall, Englewood Cliffs, New Jersey.
Comer, D. and Stevens, D. [1991], Internetworking with TCP/IP Volume III: Client-Server Programming
and Applications, Prentice Hall, Englewood Cliffs, New Jersey.
Stevens, W.R. [1990], Unix Network Programming, Prentice Hall, Englewood Cliffs, New Jersey.
Stevens, W.R. [1994]. TCP/IP Illustrated, Volume 1: The Protocols, Addison-Wesley, Massachusetts
Wright, G.R. and Stevens, W.R. [1995], TCP/IP Illustrated Volume 2: The Implementation, Addison-
Wesley., Massachusetts
Dumas, A. [1995], Programming WinSock, ISBN: 0-672-30594-1, Sams Publishing, Indianapolis, Indiana
Quinn, B. and Shute, D. [1995], Windows Sockets Network Programming, ISBN: 0-201-63372-8, Addison-
Wesley Publishing Company, Reading, Massachusetts
Roberts, D. [1995], Developing for the Internet with Winsock, ISBN 1-883577-42-X, Coriolis Group
Books.