Tenouk C & C++ |< Winsock Functions 1 | Main | Winsock Function 3 >| Site Index | Download | Linux Socket | Winsock in .NET


 

 

 

 

 

 

 

Functions, structures etc.

used in program examples of the Winsock 2 Tutorials Part 2

 

 

 

 

 

 

To learn about C function you can jump to C & C++ Functions tutorials.

 

Functions

  1. WSAGetLastError()

  2. WSACleanup()

  3. WSAEnumProtocols()

  4. inet_addr()

  5. inet_ntoa()

  6. WSPSocket()

 

WSAGetLastError()

 

Item

Description

Function

WSAGetLastError()

Use

To return the error status for the last operation that failed.

Prototype

int WSAGetLastError(void);

Parameters

This function has no parameters.

Return value

The return value indicates the error code for this thread's last Windows Sockets operation that failed.

Include file

<winsock2.h>

Library

ws2_32.lib.

Remark

The WSAGetLastError() function returns the last error that occurred for the calling thread. When a particular Windows Sockets function indicates an error has occurred, this function should be called immediately to retrieve the appropriate error code for the failing function call. This error code can be different from the error code obtained from getsockopt() SO_ERROR, which is socket-specific since WSAGetLastError() is for all thread-specific sockets.

If a function call's return value indicates that error or other relevant data was returned in the error code, WSAGetLastError() should be called immediately. This is necessary because some functions may reset the last error to 0 if they succeed, overwriting the error code returned by a previously failed function. To specifically reset the error code, use the WSASetLastError() function call with iError set to zero. A getsockopt() SO_ERROR also resets the error code to zero. The WSAGetLastError() function should not be used to check for an error value on receipt of an asynchronous message. In this case, the error value is passed in the lParam parameter of the message, and this can differ from the value returned by WSAGetLastError().

 

Table 1

 

WSACleanup()

 

Item

Description

Function

WSACleanup()

Use

Terminates use of the ws2_32.dll.

Prototype

int WSACleanup(void);

Parameters

This function has no parameters.

Return value

See below.

Include file

<winsock2.h>

Library

ws2_32.lib

Remark

See below.

 

Table 2

 

Return Values

 

The return value is zero if the operation was successful. Otherwise, the value SOCKET_ERROR is returned, and a specific error number can be retrieved by calling WSAGetLastError()Attempting to call WSACleanup() from within a blocking hook and then failing to check the return code is a common programming error in Windows Socket 1.1 applications. If an application needs to quit while a blocking call is outstanding, the application must first cancel the blocking call with WSACancelBlockingCall() then issue the WSACleanup() call once control has been returned to the application. In a multithreaded environment, WSACleanup() terminates Windows Sockets operations for all threads.

 

Error code

Meaning

WSANOTINITIALISED

A successful WSAStartup() call must occur before using this function.

WSAENETDOWN

The network subsystem has failed.

WSAEINPROGRESS

A blocking Windows Sockets 1.1 call is in progress, or the service provider is still processing a callback function.

 

Table 3

 

Remarks

 

An application or DLL is required to perform a successful WSAStartup() call before it can use Windows Sockets services. When it has completed the use of Windows Sockets, the application or DLL must call WSACleanup() to deregister itself from a Windows Sockets implementation and allow the implementation to free any resources allocated on behalf of the application or DLL. Any pending blocking or asynchronous calls issued by any thread in this process are canceled without posting any notification messages or without signaling any event objects. Any pending overlapped send and receive operations (WSASend()/WSASendTo()/WSARecv()/WSARecvFrom() with an overlapped socket) issued by any thread in this process are also canceled without setting the event object or invoking the completion routine, if specified. In this case, the pending overlapped operations fail with the error status WSA_OPERATION_ABORTED.

Sockets that were open when WSACleanup() was called are reset and automatically de-allocated as if closesocket() were called; sockets that have been closed with closesocket but that still have pending data to be sent can be affected - the pending data can be lost if the WS2_32.DLL is unloaded from memory as the application exits. To insure that all pending data is sent, an application should use shutdown() to close the connection, then wait until the close completes before calling closesocket() and WSACleanup(). All resources and internal state, such as queued un-posted-posted messages, must be de-allocated so as to be available to the next user. There must be a call to WSACleanup() for each successful call to WSAStartup(). Only the final WSACleanup() function call performs the actual cleanup; the preceding calls simply decrement an internal reference count in the WS2_32.DLL.

 

WSAEnumProtocols()

 

Item

Description

Function

WSAEnumProtocols()

Use

Retrieves information about available transport protocols.

Prototype

int WSAEnumProtocols(

  LPINT lpiProtocols,

  LPWSAPROTOCOL_INFO lpProtocolBuffer,

  LPDWORD lpdwBufferLength);

Parameters

lpiProtocols - [in] Null-terminated array of iProtocol values. This parameter is optional; if lpiProtocols is NULL, information on all available protocols is returned. Otherwise, information is retrieved only for those protocols listed in the array.

lpProtocolBuffer - [out] Buffer that is filled with WSAPROTOCOL_INFO structures.

lpdwBufferLength - [in, out] On input, number of bytes in the lpProtocolBuffer buffer passed to WSAEnumProtocols(). On output, the minimum buffer size that can be passed to WSAEnumProtocols() to retrieve all the requested information. This routine has no ability to enumerate over multiple calls; the passed-in buffer must be large enough to hold all entries in order for the routine to succeed. This reduces the complexity of the API and should not pose a problem because the number of protocols loaded on a computer is typically small.

Return value

See below.

Include file

<winsock2.h>

Library

ws2_32.lib.

Remark

Implemented as Unicode and ANSI versions, except on Windows Me/98/95. More remarks below.

 

Table 4

 

Return Values

 

If no error occurs, WSAEnumProtocols() returns the number of protocols to be reported. Otherwise, a value of SOCKET_ERROR is returned and a specific error code can be retrieved by calling WSAGetLastError().

 

Error code

Meaning

WSANOTINITIALISED

A successful WSAStartup() call must occur before using this function.

WSAENETDOWN

The network subsystem has failed.

WSAEINPROGRESS

A blocking Windows Sockets 1.1 call is in progress.

WSAEINVAL

Indicates that one of the specified parameters was invalid.

WSAENOBUFS

The buffer length was too small to receive all the relevant WSAPROTOCOL_INFO structures and associated information. Pass in a buffer at least as large as the value returned in lpdwBufferLength.

WSAEFAULT

One or more of the lpiProtocols, lpProtocolBuffer, or lpdwBufferLength parameters are not a valid part of the user address space.

 

Table 5

 

Remarks

 

The WSAEnumProtocols() function is used to discover information about the collection of transport protocols and protocol chains installed on the local computer. Since layered protocols are only usable by applications when installed in protocol chains, information on layered protocols is not included in lpProtocolBuffer. The lpiProtocols parameter can be used as a filter to constrain the amount of information provided. Often, lpiProtocols will be specified as a NULL pointer that will cause the function to return information on all available transport protocols and protocol chains. A WSAPROTOCOL_INFO structure is provided in the buffer pointed to by lpProtocolBuffer for each requested protocol. If the specified buffer is not large enough (as indicated by the input value of lpdwBufferLength ), the value pointed to by lpdwBufferLength will be updated to indicate the required buffer size. The application should then obtain a large enough buffer and call WSAEnumProtocols() again. The order in which the WSAPROTOCOL_INFO structures appear in the buffer coincides with the order, in which the protocol entries were registered by the service provider using the ws2_32.dll, or with any subsequent reordering that occurred through the Windows Sockets application or DLL supplied for establishing default TCP/IP providers.

 

inet_addr()

 

 

 

 

 

 

 

  

 

 

 

 

 

 

 

 

 

Item

Description

Function

inet_addr()

Use

Converts a string containing an (Ipv4) Internet Protocol dotted address into a proper address for the IN_ADDR structure.

Prototype

unsigned long inet_addr(const char* cp);

Parameters

cp - [in] Null-terminated character string representing a number expressed in the Internet standard ".'' (dotted) notation.

Return value

If no error occurs, inet_addr() returns an unsigned long value containing a suitable binary representation of the Internet address given. If the string in the cp parameter does not contain a legitimate Internet address, for example if a portion of an "a.b.c.d" address exceeds 255, then inet_addr() returns the value INADDR_NONE.

Include file

<winsock2.h>

Library

ws2_32.lib

Remark

See below.

 

Table 6

 

Remarks

 

The inet_addr() function interprets the character string specified by the cp parameter. This string represents a numeric Internet address expressed in the Internet standard ".'' notation. The value returned is a number suitable for use as an Internet address. All Internet addresses are returned in IP's network order (bytes ordered from left to right). If you pass in " " (a space) to the inet_addr() function, inet_addr() returns zero.

 

Internet Addresses

 

Values specified using the ".'' notation takes one of the following forms:

a.b.c.d

a.b.c

a.b

a

When four parts are specified, each is interpreted as a byte of data and assigned, from left to right, to the 4 bytes of an Internet address. When an Internet address is viewed as a 32-bit integer quantity on the Intel architecture, the bytes referred to above appear as "d.c.b.a''. That is, the bytes on an Intel processor are ordered from right to left (Little endian). The parts that make up an address in "." notation can be decimal, octal or hexadecimal as specified in the C language. Numbers that start with "0x" or "0X" imply hexadecimal. Numbers that start with "0" imply octal. All other numbers are interpreted as decimal.

 

Internet address value

Meaning

"4.3.2.16"

Decimal

"004.003.002.020"

Octal

"0x4.0x3.0x2.0x10"

Hexadecimal

"4.003.002.0x10"

Mix

 

Table 7

 

Some Note

 

The following notations are only used by Berkeley, and nowhere else on the Internet. For compatibility with their software, they are supported as specified. When a three-part address is specified, the last part is interpreted as a 16-bit quantity and placed in the right-most 2 bytes of the network address. This makes the three-part address format convenient for specifying Class B network addresses as "128.net.host''

When a two-part address is specified, the last part is interpreted as a 24-bit quantity and placed in the right-most 3 bytes of the network address. This makes the two-part address format convenient for specifying Class A network addresses as "net.host''.

When only one part is given, the value is stored directly in the network address without any byte rearrangement.

 

inet_ntoa()

 

Item

Description

Function

inet_ntoa()

Use

Converts an (Ipv4) Internet network address into a string in Internet standard dotted format.

Prototype

char* FAR inet_ntoa(struct  in_addr in);

Parameters

in - [in] Pointer to an in_addr structure that represents an Internet host address.

Return value

If no error occurs, inet_ntoa returns a character pointer to a static buffer containing the text address in standard ".'' notation. Otherwise, it returns NULL.

Include file

<winsock2.h>

Library

ws2_32.lib.

Remark

The inet_ntoa() function takes an Internet address structure specified by the in parameter and returns an ASCII string representing the address in ".'' (dot) notation as in "a.b.c.d.'' The string returned by inet_ntoa() resides in memory that is allocated by Windows Sockets. The application should not make any assumptions about the way in which the memory is allocated. The data is guaranteed to be valid until the next Windows Sockets function call within the same thread - but no longer. Therefore, the data should be copied before another Windows Sockets call is made.

 

Table 8

 

WSPSocket()

 

Item

Description

Function

WSPSocket()

Use

Creates a socket.

Prototype

SOCKET WSPSocket(

  int af,

  int type,

  int protocol,

  LPWSAPROTOCOL_INFO lpProtocolInfo,

  GROUP g,

  DWORD dwFlags,

  LPINT lpErrno);

Parameters

af - [in] Address family specification.

type - [in] Type specification for the new socket.

protocol - [in] Protocol to be used with the socket that is specific to the indicated address family.

lpProtocolInfo - [in] Pointer to a WSAPROTOCOL_INFO structure that defines the characteristics of the socket to be created.

g - [in] Reserved.

dwFlags - Socket attribute specification.

lpErrno - [out] Pointer to the error code.

Return value

See below.

Include file

<winsock2.h>

Library

ws2_32.lib.

Remark

Declared in ws2spi.h .  More remarks below.

 

Table 9

 

Return Values

 

If no error occurs, WSPSocket() returns a descriptor referencing the new socket. Otherwise, a value of INVALID_SOCKET is returned, and a specific error code is available in lpErrno.

 

Error code

Meaning

WSAENETDOWN

The network subsystem has failed.

WSAEAFNOSUPPORT

The specified address family is not supported.

WSAEINPROGRESS

Blocking Windows Sockets call is in progress, or the service provider is still processing a callback function.

WSAEMFILE

No more socket descriptors are available.

WSAENOBUFS

No buffer space is available. The socket cannot be created.

WSAEPROTONOSUPPORT

The specified protocol is not supported.

WSAEPROTOTYPE

The specified protocol is the wrong type for this socket.

WSAESOCKTNOSUPPORT

The specified socket type is not supported in this address family.

WSAEINVAL

Parameter g specified is not valid.

 

Table 10

 

Remarks

 

The WSPSocket() function causes a socket descriptor and any related resources to be allocated. By default, the created socket will not have the overlapped attribute. Windows Sockets providers are encouraged to be realized as Windows installable file systems, and supply system file handles as socket descriptors. These providers must call WPUModifyIFSHandle() prior to returning from this function. For non-file-system Windows Sockets providers, WPUCreateSocketHandle() must be used to acquire a unique socket descriptor from the ws2_32.dll prior to returning from this function.

The values for af, type, and protocol are those supplied by the application in the corresponding API functions socket() or WSASocket(). A service provider is free to ignore or pay attention to any or all of these values as appropriate for the particular protocol. However, the provider must be willing to accept the value of zero for af and type, since the ws2_32.dll considers these to be wildcard values. Also the value of manifest constant FROM_PROTOCOL_INFO must be accepted for any of af, type, and protocol. This value indicates that the Windows Sockets 2 application needs to use the corresponding values from the WSAPROTOCOL_INFO structure (iAddressFamily, iSocketType, iProtocol). The dwFlags parameter can be used to specify the attributes of the socket by using the bitwise OR operator with any of the following flags.

 

Flag

Meaning

WSA_FLAG_OVERLAPPED

This flag causes an overlapped socket to be created. Overlapped sockets can utilize WSPSend(), WSPSendTo(), WSPRecv(), WSPRecvFrom() and WSPIoctl() for overlapped I/O operations, which allow multiple operations to be initiated and in process simultaneously. All functions that allow overlapped operations also support non-overlapped usage on an overlapped socket if the values for parameters related to overlapped operation are null.

WSA_FLAG_MULTIPOINT_C_ROOT

Indicates that the socket created will be a c_root in a multipoint session. Only allowed if a rooted control plane is indicated in the protocol's WSAPROTOCOL_INFO structure.

WSA_FLAG_MULTIPOINT_C_LEAF

Indicates that the socket created will be a c_leaf in a multicast session. Only allowed if XP1_SUPPORT_MULTIPOINT is indicated in the protocol's WSAPROTOCOL_INFO structure.

WSA_FLAG_MULTIPOINT_D_ROOT

Indicates that the socket created will be a d_root in a multipoint session. Only allowed if a rooted data plane is indicated in the protocol's WSAPROTOCOL_INFO structure.

WSA_FLAG_MULTIPOINT_D_LEAF

Indicates that the socket created will be a d_leaf in a multipoint session. Only allowed if XP1_SUPPORT_MULTIPOINT is indicated in the protocol's WSAPROTOCOL_INFO structure.

 

Table 11

 

 

For multipoint sockets, exactly one WSA_FLAG_MULTIPOINT_C_ROOT or WSA_FLAG_MULTIPOINT_C_LEAF must be specified, and exactly one of WSA_FLAG_MULTIPOINT_D_ROOT or WSA_FLAG_MULTIPOINT_D_LEAF must be specified. Connection-oriented sockets such as SOCK_STREAM provide full-duplex connections, and must be in a connected state before any data can be sent or received on them. A connection to another socket is created with a WSPConnect() call. Once connected, data can be transferred using WSPSend() and WSPRecv() calls. When a session has been completed, a WSPCloseSocket() must be performed.

The communications protocols used to implement a reliable, connection-oriented socket ensure that data is not lost or duplicated. If data for which the peer protocol has buffer space cannot be successfully transmitted within a reasonable length of time, the connection is considered broken and subsequent calls will fail with the error code set to WSAETIMEDOUT. Connectionless, message-oriented sockets allow sending and receiving of datagrams to and from arbitrary peers using WSPSendTo() and WSPRecvFrom(). If such a socket is connected by using WSPConnect() to a specific peer, datagrams can be sent to that peer using WSPSend() and can be received from (only) this peer using WSPRecv(). Support for sockets with type SOCK RAW is not required but service providers are encouraged to support raw sockets whenever it makes sense to do so.

 

Shared Sockets

 

When a special WSAPROTOCOL_INFO structure (obtained through the WSPDuplicateSocket() function and used to create additional descriptors for a shared socket) is passed as an input parameter to WSPSocket(), the g and dwFlags parameters are ignored. A layered service provider supplies an implementation of this function, but it is also a client of this function if and when it calls WSPSocket() of the next layer in the protocol chain. Some special considerations apply to this function's lpProtocolInfo parameter as it is propagated down through the layers of the protocol chain.

If the next layer in the protocol chain is another layer then when the next layer's WSPSocket() is called, this layer must pass to the next layer a lpProtocolInfo that references the same unmodified WSAPROTOCOL_INFO structure with the same unmodified chain information. However, if the next layer is the base protocol (that is, the last element in the chain), this layer performs a substitution when calling the base provider's WSPSocket(). In this case, the base provider's WSAPROTOCOL_INFO structure should be referenced by the lpProtocolInfo parameter. One vital benefit of this policy is that base service providers do not have to be aware of protocol chains. This same propagation policy applies when propagating a WSAPROTOCOL_INFO structure through a layered sequence of other functions such as WSPAddressToString(), WSPDuplicateSocket(), WSPStartup(), or WSPStringToAddress().

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Further reading and digging:

 

  1. Linux and TCP/IP.

  2. Linux Sockets: Story and program examples.

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

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

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

  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 Functions 1 | Main | Winsock Function 3 >| Site Index | Download | Linux Socket | Winsock in .NET