Tenouk C & C++ | Winsock Main | Winsock Story 2 >| Site Index | Download | Linux Socket | Winsock in .NET







What do we have in this chapter?

  1. Windows Sockets (Winsock) - Introduction

  2. Winsock SPI

  3. Function Interface Model

  4. Transport Mapping Between Windows Socket API (WSA) and Windows Socket SPI (WSP) Functions

  5. Winsock Programming Considerations

  6. Socket Handles

  7. Simultaneous Access to Multiple Transport Protocols

  8. Layered Protocols and Protocol Chains

  9. Using Multiple Protocols

  10. Multiple Provider Restrictions on select()

  11. Protocol-Independent Name Resolution

  12. Registration and Name Resolution

  13. Overlapped I/O and Event Objects

  14. Scatter/Gather I/O

  15. Protocol-Independent Multicast and Multipoint

  16. Multipoint and Multicast Semantics

  17. Flow Specification Quality of Service






Winsock Tutorial


Winsock: Story 1

Winsock: Story 2

Winsock: Story 3

Winsock: Example 1

Winsock: Example 2

Winsock: Example 3

Winsock: Example 4

Winsock: Example 5

Winsock: Example 6

Winsock: Example 7

Winsock: Example 8

Winsock: Example 9

Winsock: Example 10

Winsock: Example 11

Winsock: Example 12

Winsock: Reference 1

Winsock: Reference 2

Winsock: Reference 3

Winsock: Reference 4

Another Complete and Advanced C & Winsock2 Programming Tutorial


My Training Period:          hours



The program examples if any, compiled using Visual C++ .Net (Visual studio .Net 2003).  It is low-level programming and the .Net used is Unmanaged (/clr is not set: Project menu your_project_name Properties… sub menu Configuration Properties folder General subfolder Used Managed Extension setting set to No).  This also applied to other program examples in other Modules of tenouk.com Tutorial that mentioned “compiled using Visual C++ .Net”.  Other settings are default.  Machine’s OS is standalone Windows Xp Pro SP2 except whenever mentioned.  Beware the codes that span more than one line.  Program examples have been tested for Non Destructive Test.  All information compiled for Win 2000 (NT5.0) above and for newer compilers such as Visual Studio 2005 or VS 2008 (full or express edition), please disable the Unicode character set for the project settings if there are errors regarding the types used in variable declarations.


  1. The program examples were dumped at Winsock program examples.

  2. Related functions, structures and macros used in the program examples have been dumped at Winsock function & structure 1 and Winsock function & structure 2.

  3. Other related and required information (if any) not available in no. 2 can be found at MSDN online.


Skills to be acquired:

  • Able to understand the basic of networking such as TCP/IP.

  • Able to recognize Winsock terms and definitions.

  • Able to understand Winsock implementation and operations through the APIs and program examples.

  • Able to gather, understand and use the Winsockfunctions, structures and macros in your programs.

  • Able to build programs that use the Winsock APIs.

Windows Sockets (Winsock) - Introduction


This document describes Winsock programming considerations, architecture, and capabilities available to Winsock developers. It is Windows implementation of Sockets. For more details and update, please refer to MSDN documentation. Traditional network programming implemented in Windows environment using Windows Sockets API (Winsock API - WSA). If you go through this Tutorial and try all the program examples, you will notice that WSA is similar to Linux Sockets programming with a few exception such as header files, that provided to suit Windows environment and enhances the functionalities. For example you will find the bind(), connect() and listen() are similar to the Linux Socket. This document will concentrate on Winsock version 2 and most of the program examples use the WSA.


Winsock SPI


The Winsock Service Provider Interface, or Winsock SPI (WSP), is a specialized discipline of Winsock used to create providers; transport providers such as TCP/IP or IPX/SPX (Novell Netware) protocol stacks use the Winsock SPI, as do namespace providers such as the Internet's Domain Naming System (DNS). Traditional network programming, such as enabling applications to communicate over the network, does not require use of Winsock SPI interfaces; use standard Winsock (WSA - Winsock API) interfaces instead. The Winsock SPI uses the following function prefix naming convention.






Windows Sockets Service Provider

Transport service provider entry points


Windows Sockets Provider Upcall

ws2_32.dll entry points for service providers


Windows Sockets Configuration

ws2_32.dll entry points for installation applets


Namespace Provider

Namespace provider entry points


Table 1


Function Interface Model


Windows Sockets transport and namespace–service providers are DLLs with a single exported procedure entry point for the service provider initialization function WSPStartup() or NSPStartup(), respectively. All other service provider functions are made accessible to the ws2_32.dll through the service provider's dispatch table. Service provider DLL's are loaded into memory by the ws2_32.dll only when needed, and are unloaded when their services are no longer required. The ws_32.dll file is located under the Windows system directory. For example in Windows XP SP2 it is under C:\WINDOWS\System32 directory.

The SPI also defines several circumstances in which a transport service provider calls up into the ws2_32.dll (upcalls) to obtain DLL support services. The transport service provider DLL is given the ws2_32.dll's upcall dispatch table through the UpcallTable parameter to WSPStartup(). Service providers should have their file extension changed from "DLL" to ".WSP" or ".NSP". This requirement is not strict. A service provider will still operate with the ws2_32.dll with any file extension. The Winsock SPI uses the function prefix naming convention as mentioned in the previous Table.  As described above, these entry points are not exported (with the exception of WSPStartup() and NSPStartup()), but are accessed through an exchange of dispatch tables.



Transport Mapping Between Windows Socket API (WSA) and Windows Socket SPI (WSP) Functions


The Winsock Transport SPI is similar to the Winsock API in that all of the basic socket functions appear. When a new version of a Winsock function and the original version both exist in the API, only the new version will show up in the SPI. This is illustrated in the following list.

  1. connect() and WSAConnect() both map to WSPConnect()

  2. accept() and WSAAccept() map to WSPAccept()

  3. socket() and WSASocket() map to WSPSocket()


Other API functions that are collapsed into the enhanced versions in SPI include:

  1. send()

  2. sendto()

  3. recv()

  4. recvfrom()

  5. ioctlsocket()


Support functions like htonl(), htons(), ntohl(), and ntohs() are implemented in the ws2_32.dll, and are not passed down to service providers. The same holds true for the WSA versions of these functions. Windows Sockets service provider enumeration and the blocking hook-related functions are realized in the ws2_32.dll, thus WSAEnumProtocols(), WSAIsBlocking(), WSASetBlockingHook(), and WSAUnhookBlockingHook() do not appear as SPI functions. Since error codes are returned along with SPI functions, equivalents of WSAGetLastError() and WSASetLastError() are not needed in the SPI. The event object manipulation and wait functions including WSACreateEvent(), WSACloseEvent(), WSASetEvent(), WSAResetEvent(), and WSAWaitForMultipleEvents() are mapped directly to native OS services and thus are not present in the SPI. All the TCP/IP-specific name conversion and resolution functions in Windows Sockets 1.1 such as GetXbyY(), WSAAsyncGetXByY() and WSACancelAsyncRequest(), as well as gethostname() are implemented within the ws2_32.dll in terms of the new name resolution facilities. Conversion functions such as inet_addr() and inet_ntoa() are implemented within the ws2_32.dll.


Winsock Programming Considerations


Windows Sockets 2 extends the functionality of Windows Sockets 1.1 in a number of areas. The following table summarizes the major feature changes.




Socket handles

A socket handle can optionally be a file handle in Windows Sockets 2. It is possible to use socket handles with standard Windows file I/O functions.

Simultaneous access to multiple transport protocols

Allows an application to use the familiar socket interface to achieve simultaneous access to a number of installed transport protocols.

Protocol-independent name resolution

Includes a standardized set of functions for querying and working with the myriad name resolution domains that exist today (for example DNS, SAP, and X.500).

Overlapped I/O with scatter/gather I/O

Incorporates the overlapped paradigm for socket I/O and incorporates scatter/gather capabilities as well, following the model established in Windows environments.

Protocol-independent multicast and multipoint

Applications discover what type of multipoint or multicast capabilities a transport provides and use these facilities in a generic manner.

Quality of Service (QOS)

Establishes conventions that applications use to negotiate required service levels for parameters such as bandwidth and latency. Other QOS-related enhancements include mechanisms for network-specific Quality of Service extensions.

Other frequently requested extensions

Incorporates shared sockets and conditional acceptance; exchange of user data at connection setup/teardown; and a provider-specific extension mechanism.


Table 2


Socket Handles


A socket handle can optionally be a file handle (discussed in other part of Tenouk.com Tutorial) in Windows Sockets 2. It is possible to use socket handles with ReadFile(), WriteFile(), ReadFileEx(), WriteFileEx(), DuplicateHandle(), and other functions. Not all transport service providers support this option. For an application to run over the widest possible number of service providers, it should not assume that socket handles are file handles. Windows Sockets 2 has expanded certain functions that transfer data between sockets using handles. The functions offer advantages specific to sockets for transferring data and include WSARecv(), WSASend(), and WSADuplicateSocket().


Simultaneous Access to Multiple Transport Protocols


A transport protocol must be properly installed on the system and registered with Windows Sockets to be accessible to an application. The ws2_32.dll exports a set of functions to facilitate the registration process. This includes creating a new registration and removing the existing one. When new registrations are created, the caller (that is, the stack vendor's installation script) supplies one or more filled in WSAPROTOCOL_INFO structures containing a complete set of information about the protocol. Any transport stack installed in this manner is referred to as a Windows Sockets service provider. The Platform SDK includes Sporder.exe, which allows the user to view and modify the order in which service providers are enumerated. By using this Sporder.exe, a user can manually establish a particular TCP/IP protocol stack as the default TCP/IP provider if more than one such stack is present. The Sporder.exe application exports functions from Sporder.dll to reorder the service providers. As a result, installation applications can use the interface of Sporder.dll to programmatically reorder service providers to suit their needs.

  1. Layered Protocols and Protocol Chains.

  2. Using Multiple Protocols.

  3. Multiple Provider Restrictions on Select.


Layered Protocols and Protocol Chains


Windows Sockets 2 incorporates the concept of a layered protocol: one that implements only higher-level communications functions while relying on an underlying transport stack for the actual exchange of data with a remote endpoint. An example of this type of layered protocol is a security layer that adds a protocol to the socket connection process in order to perform authentication and establish an encryption scheme. Such a security protocol generally requires the services of an underlying and reliable transport protocol such as TCP or SPX.

The term base protocol refers to a protocol, such as TCP or SPX, which is fully capable of performing data communications with a remote endpoint. A layered protocol is a protocol that cannot stand alone, while a protocol chain is one or more layered protocols strung together and anchored by a base protocol. You can create a protocol chain if you design the layered protocols to support the Windows Sockets 2 SPI at both their upper and lower edges. A special WSAPROTOCOL_INFO structure refers to the protocol chain as a whole and describes the explicit order in which the layered protocols are joined. This is illustrated in the figure below. Since only base protocols and protocol chains are directly usable by applications, they are the only ones listed when the installed protocols are enumerated with the WSAEnumProtocols() function.



Windows socket Layered Protocols and protocol chains diagram


Figure 1


Using Multiple Protocols


An application uses the WSAEnumProtocols() function to determine which transport protocols and protocol chains are present, and to obtain information about each as contained in the associated WSAPROTOCOL_INFO structure. In most instances, there is a single WSAPROTOCOL_INFO structure for each protocol or protocol chain. However, some protocols exhibit multiple behaviors. For example, the SPX protocol is message oriented (that is, the sender's message boundaries are preserved by the network), but the receiving socket can ignore these message boundaries and treat them as a byte stream. Thus, two different WSAPROTOCOL_INFO structure entries could exist for SPX- one for each behavior. In Windows Sockets 2, several new address family, socket type, and protocol values appear. Windows Sockets 1.1 supported a single address family (AF_INET) comprising a small number of well-known socket types and protocol identifiers. Windows Sockets 2 retains the existing address family, socket type, and protocol identifiers for compatibility reasons, but it also supports new transport protocols with new media types.

New, unique identifiers are not necessarily well known, but this should not pose a problem. Applications that need to be protocol-independent are encouraged to select a protocol on the basis of its suitability rather than the values assigned to their socket_type or protocol parameters. Protocol suitability is indicated by the communications attributes, such as message-versus-byte stream, and reliable-versus-unreliable, those are contained in the protocol WSAPROTOCOL_INFO structure. Selecting protocols on the basis of suitability as opposed to well-known protocol names and socket types lets protocol-independent applications take advantage of new transport protocols and their associated media types, as they become available. The server half of a client/server application benefits by establishing listening sockets on all suitable transport protocols. Then, the client can establish its connection using any suitable protocol. For example, this would let a client application be unmodified whether it was running on a desktop system connected through LAN or on a laptop using a wireless network.


Multiple Provider Restrictions on select()


The select() function is used to determine the status of one or more sockets in a set. For each socket, the caller can request information on read, write, or error status. A set of sockets is indicated by an FD_SET structure. Windows Sockets 2 allows an application to use more than one service provider, but the select() function is limited to a set of sockets associated with a single service provider. This does not in any way restrict an application from having multiple sockets open through multiple providers. There are two ways to determine the status of a set of sockets that spans more than one service provider:

When an application needs to use blocking semantics on a set of sockets that spans multiple providers, WSAWaitForMultipleEvents() is recommended. The application can also use the WSAEventSelect() function, which allows the FD_XXX network events to associate with an event object and be handled from within the event object paradigm. The WSAAsyncSelect() function is recommended when non-blocking operations are preferred. This function is not restricted to a single provider because it takes a socket descriptor as an input parameter.


Protocol-Independent Name Resolution


In developing a protocol-independent client/server application, there are two basic requirements that exist with respect to name resolution and registration:

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 Windows Sockets 2 interface adopts the model described in the topics in this section.


Registration and Name Resolution


Windows Sockets 2 a set of functions that standardizes the way applications access and use the various network naming services. When using these functions, applications need not distinguish the widely differing protocols associated with name services such as DNS, NIS, X.500, SAP, etc. To maintain full backward compatibility with Windows Sockets 1.1, the existing getXbyY() (e.g. gethostbyaddr(), gethostbyname()) and asynchronous WSAAsyncGetXbyY() (e.g. WSAAsyncGetServByName(), WSAAsyncGetProtoByNumber(), WSAAsyncGetProtoByName(), WSAAsyncGetHostByName(), WSAAsyncGetHostByAddr()) database-lookup functions continue to be supported, but are implemented in the Windows Sockets service provider interface in terms of the new name resolution capabilities.


Overlapped I/O and Event Objects


Windows Sockets 2 supports overlapped I/O and requires that all transport providers support this capability. Overlapped I/O follows the model established in Windows and can be performed only on sockets created through the WSASocket() function with the WSA_FLAG_OVERLAPPED flag set or sockets created through the socket() function. Creating a socket with the overlapped attribute has no impact on whether a socket is currently in blocking or non-blocking mode. Sockets created with the overlapped attribute can be used to perform overlapped I/O - 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 the WSARecv() or WSARecvFrom() functions 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, that data could be placed in the user's buffers immediately as it arrives. Thus, it can 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. That is, the incoming data is buffered internally until the application issues a receive call and thereby supplies a buffer into which the data can be copied. An exception to this is when the application uses 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 not to disturb the buffers in any way until 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 was completed immediately and that the corresponding completion indication 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 alertable 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 sockets that are byte-stream style, the completion indication occurs whenever the incoming data is exhausted, regardless of whether the buffers are full. 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 can be invoked several times to post receive buffers in preparation for incoming data, and the send functions can be invoked several times to queue multiple buffers to send. While the application can rely upon a series of overlapped send buffers being sent in the order supplied, the corresponding completion indications might occur in a different order. Likewise, on the receiving side, buffers can be filled in the order they are supplied, but the completion indications might occur in a different order. Canceling individual overlapped operations pending on a given socket is impossible. 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().


Scatter/Gather I/O


The WSASend(), WSASendTo(), WSARecv(), and WSARecvFrom() functions all take an array of application buffers as input parameters and can be used for scatter/gather (or vectored) I/O. This can be very useful in instances where portions of each message being transmitted consist of one or more fixed-length header components in addition to message body. Such header components need not be concatenated by the application into a single contiguous buffer prior to sending. Likewise on receiving, the header components can be automatically split off into separate buffers, leaving the message body pure. When receiving into multiple buffers, completion occurs as data arrives from the network, regardless of whether all the supplied buffers are utilized.


Protocol-Independent Multicast and Multipoint


Windows Sockets 2 provides a generic method for utilizing the multipoint and multicast capabilities of transports. This generic method implements these features just as it allows the basic data transport capabilities of numerous transport protocols to be accessed. The term, multipoint, is used hereafter to refer to both multicast and multipoint communications. Current multipoint implementations (for example, IP multicast, ST-II, T.120, and ATM UNI) vary widely. 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 differ among implementations. The WSAPROTOCOL_INFO structure for Windows Sockets 2 is used to declare the various multipoint attributes of a protocol. By examining these attributes, the programmer knows what conventions to follow with the applicable Windows Sockets 2 functions to set up, utilize, and tear down multipoint sessions. The following summarizes Winsock features that support multipoint.

The inclusion of these multipoint features in Windows Sockets 2 does not preclude an application from using an existing protocol-dependent interface, such as the Deering socket options for IP multicast.


Multipoint and Multicast Semantics


In considering how to support multipoint and multicast semantics in Windows Sockets 2 (Winsock), a number of existing and proposed schemes (including IP-multicast, ATM point-to-multipoint connection, ST-II, T.120, H.320-MCU) were examined. To enable a coherent discussion of the various schemes, it is valuable to first create a taxonomy that characterizes the essential attributes of each. In this document, the term multipoint represents both multipoint and multicast.


Flow Specification Quality of Service


Quality of Service is implemented in Windows through various system QOS components.






Further reading and digging:


  1. A complete info on Windows socket reference from MSDN which include managed and unmanaged API doc.

  2. Linux Sockets: Story and program examples.

  3. Linux and TCP/IP.

  4. Structure, enum, union and typedef story can be found struct, enum, union & typedef tutorial.

  5. For Multibytes, Unicode characters and Localization please refer to Multibyte, Unicode and wide characters (Story) and Win32 Windows & Users tutorial (Implementation).

  6. Windows data type information is Win32 - Windows data types.

  7. Check the best selling C / C++ and Windows books at Amazon.com.



Tenouk C & C++ | Winsock Main | Winsock Story 2 >| Site Index | Download | Linux Socket | Winsock in .NET