Function WSACancel AsyncRequest Winsockpas

THandle) Integer stdcall Description This function cancels an incomplete asynchronous operation. Parameters hAsyncTaskHandle A handle to identify the asynchronous operation to cancel, which is the handle previously assigned for the asynchronous operation If successful, the function will return a value of zero. Otherwise, it will return the value SOCKET_ERROR. To retrieve the specific error code, call the function WSAGetLastError(). Possible error codes are WSANOTINITIALISED, WSAENETDOWN,...

Completion Port IO Scheme

This I O scheme is the most difficult to implement, but it has considerable advantages over the I O schemes that we have described up to now. The Completion Port I O scheme scales well and offers the best performance. This scheme is only available on Windows NT 4.0, Windows 2000, and Windows XP and it is the best possible scheme for servers that have to handle thousands of connections, such as a web server. This scheme uses a Win32 completion port object that handles overlapped I O requests...

Function WSAStringToAddress Winsockpas

WSAStringToAddress(AddressString PChar AddressFamily u_int IpProtocolInfo PWSAPROTOCOL_INFO IpAddress PSockAddr IpAddressLength Pint) u_int stdcall This function converts an address in a numeric string to a socket address record. Such a record is required by Winsock functions that use the TSockAddr data structure. The function will set default values in place of missing fields of the address. For example, a missing port number will have the default value of zero. To use a particular transport...

Function WSARecvEx MSWSockpas

WSARecvEx(s TSocket buf PChar len Integer var flags Integer) Integer stdcall The function is identical to the recv() function, except that the flags parameter is a variable parameter. When a partial message is received while using the datagram protocol, the MSG_PARTIAL bit is set in the flags parameter on return from the function. s A descriptor identifying a connected socket buf A buffer to receive the incoming data len The size of buf flags An indicator specifying whether the message is fully...

Using Overlapped Routines

Overlapped routines are those functions that use the overlapped data structure. Those functions are WSAAccept(), WSASend(), WSARecv(), WSASendTo(), and WSARecvFrom(). We examined these functions earlier in this chapter, but we have left the discussion of overlapped I O until now. To use these functions to perform overlapped I O, we must specify the sockets as having the overlapped attribute set. Recall earlier that using the function WSASocket() with the flag WSA_FLAG_OVERLAPPED will create an...

Using WSAAsync Select

Calling WSAAsyncSelect() notifies Winsock to send a message to a nominated window whenever a network event occurs. You should specify which network events to detect when you make a call to WSAAsyncSelect(). Calling WSA-AsyncSelect() automatically sets the socket in non-blocking mode. The prototype for WSAAsyncSelect() is defined in Winsock2.pas as follows function WSAAsyncSelect(s TSocket hWnd HWND wMsg u_int lEvent Longint) Integer stdcall The first parameter, s, is the socket that you want to...

Enumerating Network Protocols

In some cases, it is necessary to determine what network protocols are available before your application can run. Of those installed protocols that are available on the machine, you will need to determine which protocol has the desired properties that match the application's requirements. Occasionally, the protocol that your application requires may not be present, in which case you will have to install the required protocol. We'll discuss how to install a new protocol later in this chapter. To...

Service Queries

We have discussed how to register and advertise a service on the server. From the client side's point of view, how does it locate such a service To find the service, the client has to query the name space for the service. To perform this query, your client has to call three functions WSALookupServiceBegin(), WSALookupServiceNext(), and WSALookupServiceEnd(), in that order. A call to WSALookupServiceBegin() initiates the process by setting the parameters that define the query. The function...

Starting and Closing Winsock

In this chapter, we'll build a simple application that demonstrates the two most fundamental functions in the Winsock stable, WSAStartUp() and WSACleanup(). Without exception, your application must always call WSAStartUp() before calling any other Winsock API function. If you neglect this essential step, your application will fail, sometimes in spectacular fashion. Similarly, when your application ends, it should always call WSACleanup(). At invocation, WSAStartup() performs several essential...

Resolution

When you want to communicate with a host on the Internet, you must ascertain that host's network address. Each host on the Internet has a unique IP address that has a name associated with it, usually a mnemonic or something that matches the company's name or product that has a corresponding network address. A host can have many names assigned to the same host. For example, Wordware Publishing, the publishers of this fine tome and many other excellent publications, has a host name of...

Function getnameinfo Wstcpippas

Getnameinfo(sa PSockAddr salen socklen_t host PChar hostlen DWORD serv PChar servlen DWORD flags Integer) Integer stdcall The function provides name resolution from an address to a host name. sa A pointer to a socket address structure containing the address and port number of the socket. For IPv4, the sa parameter points to a sockaddr_in structure for IPv6, the sa parameter points to a sockaddr_in6 structure. salen The length of the structure pointed to in the sa parameter host A pointer to the...

Function WSALookup ServiceNext 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 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 WSAAsync GetHostByName 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...

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...

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...

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 WSALookup ServiceBegin 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...

Function WSAReset Event 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...

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...

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,...

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....

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...

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

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...

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 WSAEvent Select 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 WSARecv From 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...

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

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 WSAClose Event 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....

Function getservbyname Winsockpas

Getservbyname name, proto PChar PServEnt stdcall The function returns information for the requested service and retrieves a pointer to the TServEnt data structure that contains information corresponding to a service name and protocol. The TServEnt record is defined as follows in Winsock2.pas servent record s_name PChar official service name s_aliases PPChar alias list s_port Smallint port number s_proto PChar protocol to use The pointer that you receive points to a record allocated by Winsock....

Function WSAConnect Winsockpas

WSAConnect s TSocket name PSockAddr namelen Integer IpCallerData LPWSABUF lpCalleeData LPWSABUF lpSQOS LPQOS lpGQOS LPQOS Integer stdcall The WSAConnect function establishes a connection to another socket application, exchanges connect data, and specifies needed Quality of Service based on the specified FLOWSPEC structure, which is not discussed here. s A descriptor identifying an unconnected socket name The name of the peer to which the socket is to be connected lpCallerData A pointer to the...

WSAEnum NetworkEventss TSocket hEvent Object Wsaevent IpNetwork Events Lpwsanetworkevents Integer stdca

The function performs three tasks 1 records network events for the selected socket, 2 clears the internal network events record, and 3 optionally resets event objects. WSAEnumNetworkEvents works with WSAEventSelect , which associates an event object with one or more network events. s A descriptor identifying the socket hEventObject An optional handle identifying an associated event object to be reset IpNetworkEvents A pointer to a _WSANETWORKEVENTS record that is filled with a record of...

Errors and errors

As you would expect, error codes, like socket functions, have a UNIX pedigree. The list of errors and their brief descriptions are in Appendix B. As well as that pedigree, we have Winsock-specific error codes resulting in a hybrid. If you examine Winsock2.pas, you will see two blocks of error codes that begin with WSA and E prefixes. These refer to Winsock and Berkeley error codes, respectively. The Berkeley error codes are mapped to their Winsock equivalents. This mapping is rather useful for...

WSARecv Msg

Like the getaddrinfo function that we examined in Chapter 4, these new functions are designed to simplify network programming by replacing some calls with one call. In the case of the ConnectEx function, you can open the connection on a specified socket and immediately send the first block of data if you elect to do so. Contrast that feature with the current way to call connect and then send or WSASend in a loop to send the data. As you would expect, the ConnectEx function will only work with...

Function setsockopt Winsockpas

Function setsockopt s TSocket level, optname Integer optval PChar optlen Integer Integer stdcall This function sets a socket option for the socket. Parameters s A descriptor identifying a socket level The level at which the option is defined. The supported levels include SOL_SOCKET and IPPROTO_TCP. optname The socket option for which the value is to be set optval A pointer to the buffer in which the value for the requested option is supplied optlen The size of the optval buffer Return Value If...

Making the Connection

After creating a socket, you are ready to exchange data or are you You cannot exchange data on sockets of the SOCK_STREAM type until the socket is in a connected state. We say that a connection exists when a local socket is connected to the remote socket. With sockets of the SOCK_DGRAM type, you do not normally need to connect with a peer before transmitting the data however, see the sidebar later in this section titled Connected and Connectionless Sockets. There are two functions that you can...

Lpfntransmitpackets function Socket TSocket lpPacket Array Lptransmitpacketselement Element Count DWOR

The function transmits in-memory data or file data over a connected socket. The function uses the operating system cache manager to retrieve file data, locking memory for the minimum time required to transmit and resulting in efficient, high-performance transmission. Socket A handle to the connected socket to be used in the transmission. Although the socket does not need to be a connection-oriented circuit, the default destination peer should have been established using the connect , WSAConnect...

Function WSACreate Event Winsockpas

WSACreateEvent WSAEVENT stdcall Description This function creates a new event object whose initial state is non-signaled. If the function succeeds, it will return the handle of the new event object. Otherwise, it will return the value WSA_INVALID_HANDLE. To retrieve the specific error code, call the function WSAGetLastError . Possible error codes are WSANOTINITIALISED, WSAENETDOWN, WSAEINPROGRESS, and WSA_NOT_ENOUGH_MEMORY. See Appendix B for a detailed description of the error codes....

TAPIs Var String

An interesting feature of LineConfigDialogEdit is the structure it uses to store configuration data. This structure, called a VarString, is defined in the TAPI Help file and the original Project JEDI translation of TAPI.pas file note that I added an additional field to point to the variable data in this structure PVarString TVarString varstring_tag packed record dwTotalSize, dwNeededSize, dwUsedSize, dwStringFormat, dwStringSize, dwStringOffset DWORD Modified by Alan C. Moore new field, next...

Winsock and Multithreading

Any implementation of Winsock is thread safe, but only if you make it so. That is, your application needs to use threads sensibly, which can be achieved by synchronization. It is up to you to develop a multithreaded Winsock application that synchronizes Winsock calls. For example, avoid a situation that could turn nasty when your application fails to notify other threads when one thread closes a socket. If you want to use multithreading in a Winsock application, consider two simple caveats...

Function WSARecv Msg MSWSockpas

LPFN_WSARECVMSG function s TSocket lpMsg LPWSAMSG lpdwNumberOfBytesRecvd LPDWORD lpOverlapped LPWSAOVERLAPPED lpCompletionRoutine LPWSAOVERLAPPED_COMPLETION_ROUTINE INT stdcall The function receives data and optional control information from connected and unconnected sockets. This function can be used in place of the WSARecv and WSARecvFrom functions. s Descriptor identifying the socket lpMsg A _WSAMSG structure based on Posix.1g specification for the msghdr structure. The structure is defined...

Function select Winsockpas

Select nfds Integer readfds, writefds, exceptfds PFdSet timeout PTimeVal Integer stdcall This function determines the status of one or more sockets. Parameters nfds This argument is ignored and included only for the sake of compatibility. readfds An optional pointer to a set of sockets to be checked for reading writefds An optional pointer to a set of sockets to be checked for writing exceptfds An optional pointer to a set of sockets to be checked for errors timeout The maximum time for select...

Querying and Modifying Attributes

In this section, we will learn how to use getsockopt and setsockopt to query and modify the attributes of a socket, respectively. Why would we want to query the attributes, or options, of a socket And why would we want to set the options The answer to both of these questions is not just to obtain the information, but to use the information gleaned from getsockopt , if we wish, to fine-tune the behavior of the socket. To fine-tune a socket's attributes, you should use setsockopt . Let's take an...

Function getpeername Winsockpas

Getpeername s TSocket name PSockAddr var namelen Integer Integer stdcall Description This function retrieves the name of the peer connected to the socket s and stores it in the TSockAddr record in the name parameter. s A descriptor identifying a connected socket name A pointer to the sockaddr_in record which is to receive the name of the peer namelen A pointer to the size of the name record If the function succeeds, it will return a value of zero. Otherwise, it will return SOCKET_ERROR. To...

Line Initialization Making a Connection with TAPI

Laying the foundation to perform even the most basic telephony operation is an involved process. First, you need to initialize TAPI itself. Next, you need to negotiate one or two TAPI versions for your application to use, taking into account the different TAPI versions and versions of service providers by different vendors. After that, you can examine each of the TAPI devices present on a computer, determining its capabilities, or you can take a shortcut and use the LINEMAPPER constant to find...

Function WSASocket Winsockpas

WSASocket af u_int atype u_int protocol u_int lpProtocollnfo PWSAPROTOCOL_INFO g TGROUP dwFlags DWORD TSocket stdcall This function creates a socket. By default, the socket created does not have the overlapped attribute set. atype A type specification for the new socket protocol A particular protocol to be used with the socket that is specific to the indicated address family lpProtocollnfo A pointer to a WSAPROTOCOL_INFO structure that defines the characteristics of the socket to be created g...