WINSOCK PROGRAMMING
- SUSHANT PAUDEL
OUTLINE
• Introduction to Winsock architecture
• Winsock DLL
• Windows sockets and Blocking I/O
• Windows Socket Extension; Setup and Cleanup Function
• Function for Handling Blocked I/O
• Asynchronous Database function
• Asynchronous I/O functions
• Error Handling Functions; Asynchronous Operation
• Using Non-Blocking socket, Non-Blocking with connect
• Select in conjunction with accept, select with rev/recvfrom and send/sendto Sending and Receiving
Data over connection.
INTRODUCTION TO WINSOCK PROGRAMMING
• Winsock (Windows Sockets) is a programming interface that allows
applications to communicate over the network in Windows
operating systems.
• It provides a set of functions, data structures, and protocols for
creating network applications.
• Winsock uses the TCP/IP protocol suite as the underlying network
protocol.
WINSOCK
● Windows Socket API, also known as Winsock,
● Winsock is a programming interface and the supporting
program that handles input/output requests for Internet
applications in a Windows operating system.
● It's called Winsock because it's an adaptation for Windows of
the Berkeley UNIX sockets interface.
WINSOCK
● Winsock exists as a data link layer, and is also known as winsock.dll in
our computers.
● Winsock is pre-installed in every Microsoft Windows operating system,
and is available for macOS too.
● The Windows Socket API includes two interfaces. T
○ he first is an API for application developers to develop apps supporting
networking.
○ In contrast, the second API is a service provider interface used to set up new
network protocols.
HOW DOES WINSOCK WORK?
● Winsock serves as a translator for basic network services, such
as send () or receive () requests.
● These requests are very generic, and Winsock functions by
converting them into application protocol-specific requests in
order to perform the required tasks.
DLL
● a dynamic link library (DLL) is a collection of small programs, which can
be called upon when needed by the executable program (EXE) that is
running.
● The DLL lets the executable communicate with a specific device such as a
printer or may contain source code to do particular functions.
ADVANTAGE OF DLL
● The advantage of DLL files is that, because they do not get loaded into
random access memory (RAM) together with the main program, space is
saved in RAM.
● When and if a DLL file is called, then it is loaded.
● For example, you are editing a Microsoft Word document, the printer
DLL file does not need to be loaded into RAM.
● If you decide to print the document, then the printer DLL file is loaded
and a call is made to print.
ADVANTAGES OF DLL
● Uses fewer resources
○ When multiple programs use the same library of functions, a DLL can reduce the
duplication of code that is loaded on the disk and in physical memory.
● Promotes modular architecture
○ A DLL helps promote developing modular programs. This helps you develop large
programs that require multiple language versions or a program that requires
modular architecture
● Eases deployment and installation
○ When a function within a DLL needs an update or a fix, the deployment and
installation of the DLL does not require the program to be relinked with the DLL.
Additionally, if multiple programs use the same DLL, the multiple programs will all
benefit from the update or the fix.
WINSOCK DLL
• The Winsock DLL (Dynamic Link Library) is a system file that contains the implementation of the
Winsock API functions.
• It provides a standardized interface for applications to access the network functionality provided by
the operating system.
• Applications link against the Winsock DLL to access the Winsock functionality.
• This dynamic linking allows multiple applications to share the same code and resources, reducing
memory consumption and improving system performance.
• The Winsock DLL provides an abstraction layer for networking operations, shielding developers
from the low-level details of network protocols and allowing them to focus on the application logic..
WINSOCK ARCHITECTURE(1.1 VS 2)
● https://www.delphipower.xyz/winsock/the_winsock_architecture.html
● https://docs.microsoft.com/en-us/windows/win32/winsock/windows-sockets-2-architecture-2
IO bit and 32 bit DLLs
(internet)
WINSOCK FILES
● The DLL (Dynamic Link Library) files installed on a Windows system to provide the
Winsock API (Application Programming Interface) to all Winsock applications:
○ WS2_32.DLL -
■ Providing Winsock 2 32-bit API and running on top of a collection of Winsock 2 SPIs (Service
Provider Interfaces).
○ WSOCK32.DLL -
■ Providing Winsock 1.1 32-bit API and running on top of the Winsock 2 API.
○ WINSOCK.DLL -
■ Providing Winsock 1.1 16-bit API and running on top of the Winsock 2 API.
○ mswsock.dll
■ is the DLL (Dynamic Link Library) file that implements the Winsock 2 SPI (Service Provider Interface)
as the Basic Server Provider in the Winsock 2 SPI architecture
ROLE OF WINSOCK:
ROLE OF WINSOCK:
● WinSock provides a library of functions. These functions can be
classified into two types:
○ Primary socket functions:
■ These functions perform specific operations to interact with the TCP/IP protocol software
■ Examples:
● – a function that requests the TCP/IP software to establish a TCP connection to a remote
server
● –a function that requests the TCP/IP software to send data..
○ Other library functions:
■ These functions help the programmer (e.g., convert an IP address from the dotted
decimal format to 32 bits).
■ The library of socket functions is located in a dynamic linked library (DLL).
WINDOWS V1 VS V2
● Winsock2 is completely backwards compatible with the original winsock
● Winsock2 introduces some new functions for new networking protocols
(like bluetooth)
● winsock.h should be used with wsock32.lib
● winsock2.h should be used with ws2_32.lib
WINDOWS SOCKETS & BLOCKING I/O
• Windows sockets, or Winsock, provides a programming interface for network
communication in Windows.
• It allows applications to create sockets, which are the endpoints for network connections.
• Blocking I/O is the default mode of operation in Winsock.
• When an application performs a blocking socket operation, such as reading or writing data,
the operation blocks the execution of the application until it completes.
• In a blocking I/O scenario, if a socket operation cannot immediately proceed, the application
will wait until the operation can be completed.
• This can lead to a delay in application responsiveness, especially when dealing with slow or
unreliable network connections.
WINDOWS SOCKET EXTENSION; SETUP AND
CLEANUP FUNCTION
• Windows Socket Extension (WSE) is a set of additional functions and features that extend the
capabilities of Winsock.
• It provides additional networking functionality beyond what is available in the core Winsock API.
• The setup function, WSAStartup(), is used to initialize the Winsock library before using any
Winsock functions.
• It informs the operating system that the application intends to use Winsock and allows the
operating system to allocate necessary resources for network communication.
• The cleanup function, WSACleanup(), is used to release the resources allocated by the Winsock
library after the application has finished using Winsock.
• It should be called when the application no longer needs network communication to free up
system resources.
FUNCTION FOR HANDLING BLOCKED I/O
• When performing blocking I/O operations, such as reading or writing data to a
socket, the application execution is blocked until the operation completes.
• To handle blocked I/O in Winsock, developers can use techniques such as
multi-threading or using a separate thread to handle I/O operations.
• This allows the application to continue executing other tasks while waiting for
the completion of I/O operations.
• By employing these techniques, the application can achieve concurrency and
responsiveness, ensuring that it can handle multiple client connections or
perform other tasks while waiting for I/O operations to finish.
ASYNCHRONOUS DATABASE FUNCTIONS
• Asynchronous database functions in Winsock allow developers to perform
database operations without blocking the application's execution.
• With asynchronous database functions, the application can initiate a
database query or operation and continue executing other tasks while
waiting for the database operation to complete.
• Once the database operation is finished, a callback function is invoked to
notify the application of the completion, and the application can then
process the results.
ASYNCHRONOUS I/O FUNCTIONS
• Winsock provides asynchronous I/O functions that allow non-blocking I/O
operations.
• With these functions, the application can initiate I/O operations and continue
executing other tasks without waiting for the operations to complete.
• Asynchronous I/O functions use an event-driven model where the application
sets up event handlers to be notified when the I/O operations complete or
when specific events occur.
• This allows the application to handle multiple I/O operations simultaneously
and efficiently manage resources.
ERROR HANDLING FUNCTIONS; ASYNCHRONOUS
OPERATIONS
• When performing asynchronous operations in Winsock, error
handling becomes crucial to handle unexpected situations and
failures.
• Winsock provides error handling functions and mechanisms to
handle errors that may occur during asynchronous operations.
• These functions allow developers to retrieve error codes, obtain
error descriptions, and take appropriate actions based on the
error conditions.
USING NON-BLOCKING SOCKET, NON-BLOCKING
WITH CONNECT
• Non-blocking sockets in Winsock allow the application to perform I/O
operations without blocking the execution flow.
• By setting a socket to non-blocking mode, the application can initiate I/O
operations and continue executing other tasks without waiting for the
operations to complete.
• Non-blocking sockets are particularly useful in scenarios where the
application needs to handle multiple connections or perform concurrent I/O
operations.
SELECT IN CONJUNCTION WITH ACCEPT, SELECT
WITH RECV/RECVFROM AND SEND/SENDTO:
• The select function in Winsock is used to monitor multiple sockets for
readability, writability, or exceptional conditions.
• It allows the application to efficiently multiplex I/O operations on multiple
sockets, handling multiple connections or I/O events simultaneously.
• The select function can be used in conjunction with other socket functions like
accept, recv/recvfrom, and send/sendto to manage and process incoming
and outgoing data on multiple sockets.
SOCKETS
SOCKETS - BASIC CONCEPTS
● A socket is an endpoint of communication to which a name
may be bound
● Each socket in use has a type and an associated process
● Sockets exist within communication domains.
● The Windows Sockets facilities support a single
communication domain: the Internet domain, which is used by
processes which communicate using the Internet Protocol
Suite.
SOCKETS - BASIC CONCEPTS
● Two types of sockets currently are available to a user.
○ A stream socket
■ provides for the bi-directional, reliable, sequenced, and
unduplicated flow of data without record boundaries
○ A datagram socket
■ supports bi-directional flow of data which is not promised to be
sequenced, reliable, or unduplicated.
BROADCASTING
● By using a datagram socket, it is possible to send
broadcast packets on many networks supported by the
system
● Broadcast messages can place a high load on a
network, since they force every host on the network to
service them.
BLOCKING/NON BLOCKING & DATA VOLATILITY
● Blocking means invoking a function which does not return until the
associated operation is completed
● 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.
BLOCKING/NON BLOCKING & DATA VOLATILITY
● Within a Windows Sockets implementation, a blocking operation which cannot be completed
immediately is handled as follows.
○ The DLL initiates the operation, and then enters a loop in which it dispatches any Windows messages
and then checks for the completion of the Windows Sockets 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 pseudocode for
the various functions.
○ 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 Windows Sockets call. Two functions are provided to
assist the programmer in this situation.
■ WSAIsBlocking() may be called to determine whether or not a blocking Windows Sockets call is in progress.
■ WSACancelBlockingCall() may be called to cancel an in-progress blocking call, if any
● Any other Windows Sockets function.which is called in this situation will fail with the error WSAEINPROGRESS.
ASYNCHRONOUS SELECT() MECHANISM
● The WSAAsyncSelect() API allows an application to register an interest in one or
many network events.
● WSAAsyncSelect() allows interest to be declared in the following conditions for a
particular socket:
○ Socket readiness for reading
○ Socket readiness for writing
○ Out-of-band data ready for reading
○ Socket readiness for accepting incoming connection
○ Completion of non-blocking connect()
○ Connection closure
ASYNCHRONOUS SUPPORT ROUTINES
● The asynchronous "database" functions allow applications to request information in
an asynchronous manner.
● Some network implementations and/or configurations perform network based
operations to resolve such requests.
○ WSAAsyncGetXByY() functions allow application developers to request services which would
otherwise block the operation of the whole Windows environment if the standard Berkeley
function were used.
○ WSACancelAsyncRequest() function allows an application to cancel any outstanding
asynchronous request.
HOOKING BLOCKING METHODS
● The WSASetBlockingHook() provides the ability to substitute a named
routine which the Windows Sockets implementation is to use when
relinquishing the processor during a "blocking" operation.
ERROR HANDLING
● WSAGetLastError()
○ Provides error code on a per thread basis
● A Windows Sockets implementation must not return any value
which is not enumerated in the table of legal Windows Sockets
errors given in Error Codes
ACCESSING A WINDOWS SOCKETS DLL FROM AN INTERMEDIATE DLL
● There are (at least) two ways to accomplish this.
○ to have calls similiar to WSAStartup() and WSACleanup()
■ WSAStartup() - to set up task-specific data structures
■ WSACleanup() - to free any resources allocated for the task.
○ To build a table of task handles, which are obtained from
the GetCurrentTask() Windows API, and at each entry point
into the intermediate DLL check whether WSAStartup() has
been called for the current task, then call WSAStartup() if
necessary.
SOCKET FUNCTIONS
The Windows Sockets specification includes the following Berkeley-style socket routines:
● accept() An incoming connection is acknowledged and associated with an
immediately created socket. The original socket is returned to the listening state.
● bind() Assign a local name to an unnamed socket.
● closesocket() Remove a socket descriptor from the per-process object reference
table. Only blocks if SO_LINGER is set.
● connect() Initiate a connection on the specified socket.
SOCKET FUNCTIONS
● getpeername() Retrieve the name of the peer connected to
the specified socket descriptor.
● getsockname() Retrieve the current name for the specified
socket
● getsockopt() Retrieve options associated with the specified
socket descriptor.
● htons() Convert a 16-bit quantity from host byte order to
network byte order.
● inet_addr() Converts a character string representing a number
in the Internet standard ``.'' notation to an Internet address
value.
SOCKET FUNCTIONS
● inet_ntoa() Converts an Internet address value to an ASCII string in``.''
notation i.e. ``a.b.c.d''.
● ioctlsocket() Provide control for descriptors.
● listen() Listen for incoming connections on a specified socket.
● ntohl() Convert a 32-bit quantity from network byte order to host byte
order.
● ntohs() Convert a 16-bit quantity from network byte order to host byte
order.
● recv()* Receive data from a connected socket.
● recvfrom()* Receive data from either a connected or unconnected
socket.
● select()* Perform synchronous I/O multiplexing.
SOCKET FUNCTIONS
● send()* Send data to a connected socket.
● sendto()* Send data to either a connected or
unconnected socket.
● setsockopt() Store options associated with the specified
socket descriptor.
● shutdown() Shut down part of a full-duplex connection.
● socket() Create an endpoint for communication and
return a socket descriptor.
DATABASE FUNCTIONS
● gethostbyaddr()* Retrieve the name(s) and address corresponding to a
network address.
● gethostname() Retrieve the name of the local host.
● gethostbyname()* Retrieve the name(s) and address corresponding to a
host name.
● getprotobyname()* Retrieve the protocol name and number
corresponding to a protocol name.
● getprotobynumber()* Retrieve the protocol name and number
corresponding to a protocol number.
● getservbyname()* Retrieve the service name and port corresponding to
a service name.
● getservbyport()* Retrieve the service name and port corresponding to a
MICROSOFT WINDOWS-SPECIFIC EXTENSION FUNCTIONS
● WSASetBlockingHook() "Hook" the blocking method used by the
underlying Windows Sockets implementation
● WSAUnhookBlockingHook() Restore the original blocking function
● WSAStartup() Initialize the underlying Windows Sockets DLL.
● WSACleanup() Sign off from the underlying Windows Sockets DLL.
● WSAIsBlocking() Determine if the underlying Windows Sockets DLL is
already blocking an existing call for this thread
● WSACancelBlockingCall() Cancel an outstanding "blocking" API call
● WSAGetLastError() Obtain details of last Windows Sockets API error
● WSASetLastError() Set the error to be returned by a subsequent
THANK YOU!
- SUSHANT PAUDEL