function WSACancelBlockingCall Winsockpas

WSACancelBlockingCall integer Description This function cancels a blocking call that is in progress and any outstanding blocking operation for this thread. You would use this function in two cases In the first case, suppose our application is processing a message that has been received while a blocking call is in progress. In this case, WSAIsBlocking will be TRUE. In the second case, suppose that a blocking call is in progress, and Winsock has called back to the application's blocking hook...

function WSALookupServiceNext Unit Winsockpas

WSALookupServiceNext hLookup HANDLE dwControlFlags DWORD var lpdwBufferLength DWORD lpqsResults LPWSAQUERYSETW Integer stdcall We call this function with the hLookup parameter assigned by a previous call to WSALookupServiceBegin to retrieve the requested service information. The provider will pass back a pointer to the WSAQUERYSET record in the lpqs-Results buffer. The client should continue to call this function until it returns WSA_E_NO_MORE, indicating that all of the WSAQUERYSET records...

function lineConfigDialogEdit TAPlpas

function lineConfigDialogEdit dwDeviceID DWORD hwndOwner HWND lpszDeviceClass LPCSTR IpDeviceConfigIn Pointer dwSize DWORD IpDeviceConfigOut PVarString Longint stdcall This function causes the provider of the specified line device to display a dialog box attached to hwndOwner of the application that allows the user to configure parameters related to the line device. dwDeviceID A DWORD holding the line device to be configured

function connect Winsockpas

connect s TSocket name PSockAddr namelen Integer Integer stdcall Description This function establishes a connection to a peer. Parameters name The name of the socket in the sockaddr_in structure namelen The length of the name Return Value If the function succeeds, it will return a value of zero. Otherwise, it will return SOCKET_ERROR. To retrieve the specific error code, call the function WSAGetLastError. Possible error codes are WSANOTINITIALISED, WSAE-NETDOWN, WSAEADDRINUSE, WSAEINTR,...

function WSAAccept Winsockpas

WSAAccept s TSocket addr PSockAddr addrIen PInteger IpfnCondition LPCONDITIONPROC dwCaIIbackData DWORD TSocket stdcaII This function performs the same operation as accept . In addition, the function has extra functionality in three areas Conditionally accepts a connection based on the return value of a condition function Allows transfer of connection data Parameters s A descriptor for the socket that was called with the listen function addr An optional pointer to a buffer that receives the...

Event Notification

This method to implement overlapped I O uses the event objects with WSAOVERLAPPED data structures. To map an event with the WSAOVER-LAPPED structure, you should call WSACreateEvent and assign that event to the overlapped data structure. When you call a function such as WSARecv with a valid WSAOVERLAPPED structure, it returns immediately, usually with a SOCKET_ERROR. This is normal behavior, and your application must call WSAGetLastError to check if the error is WSA_IO_PENDING, which means that...

Summary

In this chapter, we covered the origins of the Internet, which led to the establishment of TCP IP as the protocol suite of choice. We reviewed the evolution of Winsock from BSD Sockets and briefly covered the Winsock 2 architecture and its new features. To simplify coverage of the Winsock 2 API in the following chapters, the functions are grouped by the following topics Table 1-1 Function groups For the majority of these functions, we'll demonstrate their usage with example code. NOTE These...

function WSAAsyncGetHostByName Winsockpas

WSAAsyncGetHostByName hWnd HWND wMsg u_int name, buf PChar buflen Integer HANDLE stdcall This function asynchronously retrieves information corresponding to a host name. hWnd The handle of the window that should receive a message when the asynchronous request completes wMsg The message to receive when the asynchronous request completes name A pointer to the NULL-terminated name of the host buf A pointer to the data area to receive the THostEnt data. The size of the buffer must be larger than...

function WSAEnumNameSpaceProviders Winsockpas

WSAEnumNameSpaceProviders var IpdwBufferLength DWORD IpnspBuffer LPWSANAMESPACE_INFOW Integer stdcall This function retrieves information about available name spaces on the local machine. lpdwBufferLength On input, the number of bytes contained in the buffer pointed to by lpnspBuffer. On output if the API fails and the error is WSAE-FAULT , the minimum number of bytes to pass for the lpnspBuffer to retrieve all the requested information. On input, the buffer must be large enough to hold all of...

function WSASetEvent Winsockpas

WSASetEvent hEvent WSAEVENT BOOL stdcall Description This function sets the state of the specified event object to be signaled. Parameters hEvent Identifies an open event object handle. Return Value If the function succeeds, the return value will be TRUE. If the function fails, the return value will be FALSE. To get extended error information, call WSAGet-LastError . Possible errors are WSANOTINITIALISED, WSAENETDOWN, WSAEINPROGRESS, and WSA_INVALID_HANDLE. See Appendix B for a detailed...

procedure GetAcceptExSockaddrs MSWSockpas

GetAcceptExSockaddrs lpOutputBuffer LPVOID dwReceiveDataLength, dwLocalAddressLength, dwRemoteAddressLength DWORD var LocalSockaddr LPSOCKADDR var LocalSockaddrLength Integer RemoteSockaddr LPSOCKADDR var RemoteSockaddrLength Integer stdcall The procedure parses the data obtained from a call to the AcceptEx function and passes the local and remote addresses to a sockaddr structure. lpOutputBuffer A pointer to a buffer that will receive the first block of data sent on a connection resulting from...

Miscellaneous Conversion Functions

The functions we have just examined relate to translating numbers between different endian formats. What about IP addresses and their matching host names In this section, we will look at functions that convert an IP dotted address into a network address and vice versa. Be aware, however, that these functions only translate between different formats and don't actually resolve names and IP addresses we will examine those functions that do later in this chapter. inet_addr cp PChar u_long stdcall...

Three Notification Mechanisms

When you call the lineInitializeEx function to establish the communication link we've been discussing, you must select one of three notification mechanisms. Any of these mechanisms will allow your application to receive information about telephony events. The three mechanisms that TAPI provides are Hidden Window, Event Handle, and Completion Port. We'll discuss each mechanism beginning with the means of invoking it, its basic qualities, and the issues or constraints associated with it. To...

function lineClose TAPlpas

function lineClose hLine HLINE Longint stdcall Description This function closes the specified open line device. Parameters hLine A handle HLINE to the open line device to be closed. After the line has been successfully closed, this handle is no longer valid. Returns zero if the request is successful or a negative error number if an error has occurred. Possible return values are LINEERR_INVALLINEHANDLE, LINEERR_RESOURCEUNAVAIL, LINEERR_NOMEM, LINEERR_UNIN-ITIALIZED, LINEERR_OPERATIONFAILED, and...

function WSASend Winsockpas

WSASend s TSocket IpBuffers LPWSABUF dwBufferCount DWORD var IpNumberOfBytesSent DWORD dwFIags DWORD IpOverlapped LPWSA-OVERLAPPED IpCompletionRoutine LPWSAOVERLAPPED_COMPLETION ROUTINE Integer stdcaII This function extends the functionality provided by the send important areas It can be used in conjunction with overlapped sockets to lapped send operations. It allows multiple send buffers to be specified, making it scatter and gather type of I O. s A descriptor identifying a connected socket...

Duplicated Sockets

Winsock 2 introduces a new function, WSADuplicateSocket , to allow a server to farm out another socket to serve a client while attending to other requests. A server, or a parent process, calls WSADuplicateSocket to obtain a special TWSAPROTOCOL_INFO record. The server then passes the contents of this record via a mechanism usually by an InterProcess Call to a child process, which in turn uses it in a call to WSASocket to obtain a descriptor for the duplicated socket. Note that the child process...

Raw Sockets 1

In this short section, we will expose raw sockets. Raw sockets are based on the SOCK_RAW socket type in the AF_INET and AF_ATM address families. Unlike other socket types, such as SOCK_STREAM and SOCK_DGRAM, support for SOCK_RAW is purely optional in the AF_INET address family. That is, it is an optional feature in the Winsock hierarchy that not all vendors support. Fortunately for network developers, Microsoft supports this socket type for both address families, but there is a sting in the...

function WSARecvDisconnect Winsockpas

WSARecvDisconnect s TSocket IpInboundDisconnectData LPWSABUF Integer stdcaII This function disables reception on a connection-oriented socket and retrieves the disconnect data from the remote party. s A descriptor identifying a socket lpInboundDisconnectData A pointer to the incoming disconnect data Return Value If the function succeeds, it will return zero. Otherwise, it will return a value of SOCKET_ERROR. To retrieve the error code, call the function WSAGetLast-Error . Possible error codes...

function WSARecv Winsockpas

WSARecv s TSocket IpBuffers LPWSABUF dwBufferCount DWORD var IpNumberOfBytesRecvd, IpFIags DWORD IpOverlapped LPWSAOVERLAPPED IpCompIetionRoutine LPWSAOVERLAPPED_COMPLETION_ROUTINE Integer stdcaII This function receives data from a connected socket and extends functionality over the recv function in three important areas It can be used with overlapped sockets to perform overlapped receive operations. It allows multiple receive buffers to be specified, making it applicable to the scatter and...

function WSASetService Winsockpas

WSASetService lpqsRegInfo LPWSAQUERYSETW essoperation WSAESETSERVICEOP dwControlFlags DWORD Integer stdcall This function registers or removes a service instance within one or more name spaces. IpqsRegInfo Specifies service information for registration or identifies service for removal essoperation An enumeration value, which may be one of the values in Table 4-5 dwControlFlags This parameter can be set to either no value or SERVICE_ MULTIPLE. The function combines the value of dwControlFlags...

Give Me Your ID

Closely related to the lineOpen function is the lineGetID function. Earlier we discussed the LINEMAPPER constant, which locates an appropriate device given a list of requested services. Given the current line handle, the lineGetID function will retrieve a line device ID the real line device ID of the opened line. You can also use this function to retrieve the device ID of a phone device or media device. The latter might include such device classes as Waveform, MIDI, phone, and line. Any of...

Return Value

If the function fails, the return value will be WSA_WAIT_FAILED. To obtain extended error information, call WSAGetLastError . The return value upon success is one of the values in Table 5-9. Table 5-9 Return values for WSAWaitForMultipleEvents Table 5-9 Return values for WSAWaitForMultipleEvents WSA WAIT EVENT 0 to WSA_WAIT_EVENT_0 cEvents- 1 If fWaitAll is TRUE, the return value indicates that the state of all specified event objects is signaled. If fWaitAll is FALSE, the return value minus...

function WSALookupServiceBegin Winsockpas

LPWSAQUERYSETW dwControlFlags DWORD var IphLookup HANDLE Integer stdcall This function initiates a client query that is constrained by the information contained within a WSAQUERYSET record. The function only returns a handle, which WSALookupServiceNext uses to get the actual results. As mentioned above, you use a pointer to the WSAQUERYSET record as an input parameter to WSALookupServiceBegin to qualify the query. Table 4-10 explains how you would use the WSAQUERYSET structure to construct a...

Opening a Line Device

Now that we have laid the proper foundation, we are ready for the final step, which is actually opening a line device. Once you have obtained a line device's capabilities, your application must actually open that line device before it can access its telephony functions. Keep this in mind As defined by TAPI, a line device is an abstraction of a line. Therefore, opening a line and opening a line device can be thought of as interchangeable. When an application has opened a line device...

Evolution of Winsock

Winsock to the rescue Development of network-aware applications became so problematic that those leaders in the Windows communications industry organized a Birds of a Feather BOF conference at a prestigious trade show in 1991. At the end of the conference, delegates set up a committee to investigate the creation of a standard API for TCP IP for Windows. This led to a specification that became Windows Sockets. The specification used much of BSD Sockets as its foundation. Windows 3.1 was a...

function WSAResetEvent Winsockpas

WSAResetEvent hEvent WSAEVENT BOOL stdcall This function resets the state of the specified event object to non-signaled. Parameters hEvent Identifies an open event object handle Return Value If the function succeeds, the return value will be TRUE. If the function fails, the return value will be FALSE. To get extended error information, call WSAGetLastError . Possible error codes are WSANOTINITIALISED, WSAENETDOWN, WSAEINPROGRESS, and WSA_INVALID_HANDLE. See Appendix B for a detailed description...

function WSASendDisconnect Winsockpas

WSASendDisconnect s TSocket IpOutboundDisconnectData LPWSABUF Integer stdcaII This function initiates termination of the connection on the connection-oriented socket and sends disconnect data, if any. TIP WSASendDisconnect does not close the socket, and resources attached to the socket will not be freed until closesocket is invoked. s A descriptor identifying a socket lpOutboundDisconnectData A pointer to the outgoing disconnect data Return Value If the function succeeds, it will return zero....

Modifying IO Behavior

So far, we have described how to query and set the attributes of a socket using options. In the rest of this chapter, we will consider how you might modify the I O behavior of a socket. There are two functions with which you can modify the I O behavior ioctlsocket and WSAIoctl . These functions are defined in Winsock2.pas, and their prototypes are listed as follows function ioctlsocket s TSocket cmd Longint var argp u_long Integer stdcall function WSAIoctl s TSocket dwIoControlCode DWORD...

getnameinfo

In the case of gethostbyname , you would use getaddrinfo instead. The nice thing about these new functions is that they work with IPv4 and IPv6, which will enable you to support Winsock applications for IPv4 and IPv6. Not surprisingly, Microsoft calls these new functions agnostic functions. However, there are still traps for the unwary, which we will explore in the next section. Now that we know the reasons for moving away from IPv4 to IPv6, we need to address the question, how different is...

Info

htonl, htons, ntohl, WSAHtonl, WSAHtons, WSANtohl, WSANtohs Example Listing 3-1 demonstrates how to use these functions htonl , htons , ntohl , and ntohs . This example requires a number on the command line. For example, you would type the following Listing 3-1 Using htonl , htons , ntohl , and ntohs Example EX31 demonstrates how to convert numbers from network to host order and vice versa. The following functions are used htons , htonl , ntohs and ntohl . netshort A 16-bit integer in network...

Translation Functions

Computers store numbers through byte ordering. There are two ways to represent numbers, little endian and bigendian. Intel processors store numbers in little endian format from the least significant byte to the most significant byte right to left . On other processors such as those that run some UNIX systems , numbers are in big-endian format from the most significant byte to the least significant byte left to right. Since the Internet is a heterogeneous network of different computers,...

function WSAHtons Winsockpas

WSAHtons s TSocket hostshort u_short lpnetshort pu_short u_int stdcall Description This function converts a 16-bit number in host byte order and returns a 16-bit number pointed to by the lpnetshort parameter in network byte order for the socket descriptor s. hostshort A 16-bit number in host byte order lpnetshort A pointer to a 16-bit number in network byte order Return Value If the function succeeds, it will return zero. If the function fails, the return value will be SOCKET_ERROR. To retrieve...

Preparation

Before a server can service requests from clients on any of these Internet protocols, it has to perform certain operations before it is ready to serve. To begin with, a server is not required to resolve its own address, so that step falls away. In addition, a server does not require either the connect or the WSAConnect functions because it will be listening as opposed to connecting. However, a server follows the same steps as the client to create a socket, but after creating a socket, a server...

The Winsock Architecture

As you have no doubt already deduced, the main difference between the two Winsock versions we're discussing is that Winsock 1.1 uses the TCP IP protocol suite exclusively, whereas Winsock 2 supports other protocols, such as AppleTalk, IPX SPX, and many others, as well as TCP IP. Figure 1-4 shows the simple interaction between a Winsock 1.1 application with the WINSOCK.DLL or WSOCK.DLL. Because of its support for multiple protocols, the architecture of Winsock 2 is necessarily more complex....

Option IPTTL

You should use this option to specify the time to live in the TTL field in the IP header. In other words, your goal is to limit the number of routers that the packet can traverse before it is discarded. How does this work As the router receives the packet, it examines the header and decrements the TTL field by one. When the field becomes zero, the router discards the packet. For example, setting the option to two means that the packet can only do three hops remember, you start the count from...

Using Select

Use the select function to manage a collection of sockets. The function is a Winsock derivative of the select function in the Berkeley socket implementations and is provided for compatibility reasons for Berkeley socket applications. The function is useful on Windows CE, where the current version of Winsock does not provide asynchronous sockets and event objects. The select function is a synchronous version of WSAAsyncSelect , but is much more difficult to program. WSAAsyncSelect and...

Address and String Conversion Functions

In this section, we will examine briefly the WSAAddressToString and WSA-StringToAddress functions. Neither function exists in Winsock 1.1. These functions convert a TSockAddr data structure into a string and vice versa using the specified transport protocol. In a later section, we'll discuss protocol independence, which is a basic feature of the Winsock 2 architecture. As well as specifying a transport protocol, such as TCP and UDP, we need to specify the address family that supports the...

function AcceptEx MSWSockpas

AcceptEx sListenSocket, sAcceptSocket TSocket lpOutputBuffer LPVOID dwReceiveDataLength, dwLocalAddressLength, dwRemoteAddressLength DWORD var lpdwBytesReceived DWORD lpOverlapped POVERLAPPED BOOL stdcall The function accepts a new connection, returns the local and remote address, and receives the first block of data sent by the client application. Be aware that this function is not supported on Windows 95 98 Me. sListenSocket This is a descriptor identifying a socket that has already been...

datagrams have died

Your ping program must also check the code type returned by the ping server. It should be type 0 for an echo reply. Sometimes, though, the ping server can return types other than 0, so it is necessary for your ping application to check this type code, as the following snippet of code from Listing 5-9 shows if IcmpHeader._Type lt gt ICMP_ECHOREPLY then begin WriteLn Format 'Non-echo type d recvd', IcmpHeader ._type Exit end Dialogs, SysUtils, Windows, Winsock2, ICMP ECHOREPLY 0 ICMP type echo...

Info 2

Example EX42 demonstrates how to use WSAStringToAddress and WSAAddressToString. No command line parameters are required. uses Windows, WinSock2, ComObj, SysUtils AddrStr array 0 MAXGETH0STSTRUCT - 1 of char AddrSize Integer Res DWORD if WSAStartUp 0202, WSAData 0 then LocalAddr.sin_family AF_INET AddrSize SizeOf TSockAddrIn Res WSAStringToAddress PChar HostAddress , AF_INET, NIL, LocalAddr, AddrSize if Res SOCKET_ERROR then WriteLn 'Call to WSAStringToAddress failed with error ' SysErrorMessage...

Registering a Service

Before any potential clients can communicate with your service, you need to advertise it. This is analogous to advertising a product or service in the business world. To advertise a new service to your potential clients on the network, you need to call two functions, WSAInstallServiceClass to install your new service class and WSASetService to register an instance of your service. You must call these functions in that order. The WSAInstallServiceClass function creates a service class for the...

function WSAHtonl Winsockpas

WSAHtonl s TSocket hostlong u_long lpnetlong pu_long u_int stdcall This function takes a 32-bit number in host byte order and returns a 32-bit number pointed to by the Ipnetlong parameter in network byte order for the socket descriptor s. hostlong A 32-bit number in host byte order lpnetlong A pointer to a 32-bit number in network byte order Return Value If the function succeeds, it will return zero. If the function fails, the return value will be SOCKET_ERROR. To retrieve the specific error...

function WSAEnumProtocols Winsockpas

WSAEnumProtocoIs IpiProtocoIs Pint IpProtocolBuffer PWSAPROTOCOL_INFO IpdwBufferLength PDWORD u_int stdcaII This function enumerates all available transport protocols and protocol chains installed on the local machine. You may use the lpiProtocols parameter as a filter to constrain the amount of information provided. Normally you set this parameter to NIL, which will cause the function to return information on all available transport protocols and protocol chains. A TWSAProtocolInfo record is...

Blocking and Asynchronous Resolution

Winsock provides two sets of functions to resolve hosts, protocols, and services. The first set uses the concept of a blocking operation, and the second set uses asynchronous mode. Using a blocking function in the main thread of the application causes the user interface to freeze during resolution. That is, the operation blocks until it gets a result, preventing any input from the keyboard or mouse. Freezing the user interface can be inconvenient and possibly not user friendly. However, the...

function WSAEventSelect Winsockpas

WSAEventSelect s TSocket hEventObject WSAEVENT INetworkEvents Longint Integer stdcall This function associates an event with the supplied set of network events. Parameters s A descriptor identifying the socket hEventObject A handle identifying the event object to be associated with the supplied set of FD_XXX network events INetworkEvents A bit mask that specifies the combination of FD_XXX network events in which the application has interest If the function succeeds, it will return zero. If the...

function WSARecvFrom Winsockpas

WSARecvFrom s TSocket IpBuffers LPWSABUF dwBufferCount DWORD var IpNumberOfBytesRecvd, IpFIags DWORD IpFrom PSockAddr IpFromIen PInteger IpOverIapped LPWSAOVERLAPPED IpCompIetionRoutine LPWSAOVERLAPPED_COMPLETION_ROUTINE Integer stdcaII This function extends the functionality provided by the recvfrom 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...

function getaddrinfo Wstcpippas

getaddrinfo nodename, servname PChar hints PAddrlnfo var res PAddrlnfo Integer stdcall This function provides protocol-independent translation from host name to address. nodename A pointer to a NULL-terminated string containing a host name or a numeric host address string. The numeric host address string is a dotted decimal IPv4 address or an IPv6 hexadecimal address. servname A pointer to a NULL-terminated string containing either a service name or port number hints A pointer to an addrinfo...

Introduction to TAPI

Telephony has a magic ring bad pun , just like telepathy no wonder a recent television commercial in the United States played with these two similar-sounding words. The same sense of magic that must have struck early telephone users to be able to talk with someone in another town or country struck computer users when they were first able to place calls from their desktop machines without lifting the phone handset from its cradle. Of course, this capability depends on certain hardware and...

Breaking the Connection 1

When data exchange is complete, you should close the connection with the remote peer and free any sockets allocated for that exchange. To free these sockets, you should call the shutdown and closesocket functions, in that order. Calling shutdown notifies the remote peer that you are done with the data exchange and disables data communication on the socket, which is either receiving or sending data. If you set the how parameter in shutdown to SD_RECEIVE, the affected socket will not receive any...

function WSACloseEvent Winsockpas

WSACloseEvent hEvent WSAEVENT BOOL stdcall Description This function closes an open event object handle. Parameters hEvent Identifies an open event object handle Return Value If the function succeeds, it will return TRUE. If the function fails, it will return FALSE. To retrieve the specific error code, call the function WSAGetLast-Error . Possible error codes are WSANOTINITIALISED, WSAENETDOWN, WSAEINPROGRESS, and WSA_INVALID_HANDLE. See Appendix B for a detailed description of the error codes....