Winsock 2 provides two useful support functions named WSAAddressToString and WSAStringToAddress that provide a protocol-independent method to convert a SOCKADDR structure of a protocol to a formatted character string and vice versa. Since these functions are protocol-independent, they require the transport protocol to support the string conversions. Currently these functions work only for the AF_INET and AF_ATM address families. The WSAAddressToString function is defined as
INT WSAAddressToString( LPSOCKADDR lpsaAddress, DWORD dwAddressLength, LPWSAPROTOCOL_INFO lpProtocolInfo, OUT LPTSTR lpszAddressString, IN OUT LPDWORD lpdwAddressStringLength ); |
The lpsaAddress parameter represents a SOCKADDR structure for a particular protocol that contains the address to convert to a string. The dwAddressLength parameter specifies the size of the first parameter's structure, which can vary in size with different protocols. The lpProtocolInfo is an optional parameter that represents a protocol provider. Protocol providers can be retrieved from the WSAEnumProtocols API function, as described in Chapter 5. If you specify NULL, the call uses the provider of the first protocol supporting the address family indicated in lpsaAddress. The lpszAddressString parameter is a buffer that receives the human-readable address string. The lpdwAddressStringLength parameter represents the size of lpszAddressString. On output, it returns the length of the string actually copied into lpszAddressString. If the supplied buffer isn't large enough, the function fails with error WSAEFAULT and the lpdwAddressStringLength parameter is updated with the required size in bytes.
Conversely, the WSAStringToAddress API function takes a human-readable address string and converts it to a SOCKADDR structure. WSAStringToAddress is defined as
INT WSAStringToAddress( LPTSTR AddressString, INT AddressFamily, LPWSAPROTOCOL_INFO lpProtocolInfo, LPSOCKADDR lpAddress, LPINT lpAddressLength ); |
The AddressString parameter is a human-readable address string. Table 6-3 describes the format for this string for the current supported protocols.
Table 6-3. Address string formats
Address Family | String Format |
---|---|
IP | XXX.XXX.XXX.XXX:Y—where X represents an octet in an IP address string and Y represents a port number |
ATM | NNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNN— where the 40 N characters represent a 20-byte ATM address in hexadecimal notation |