Winsock2 Study (a) the use of the getaddrinfo () function

Source: Internet
Author: User

The Winsock2 extended getaddrinfo () function provides an address acquisition and representation method that is not protocol-independent, and the contents of the address structure are represented in the order of the network bytes. Getaddrinfo () Use structure addrinfo to describe address information, see the structure of addrinfo

1typedefstructAddrinfo {2   intai_flags;3   intai_family;4   intAi_socktype;5   intAi_protocol;6 size_t Ai_addrlen;7   Char*Ai_canonname;8   structSOCKADDR *ai_addr;9   structAddrinfo *Ai_next;Ten} Addrinfoa, *paddrinfoa;
Addrinfo Structural Body

The meaning represented by each struct member is not explained first. See the Declaration of the Getaddrinfo () function

1 int Wsaapi getaddrinfo (2  _in_opt_  pcstr pnodename,3  _in_opt_  pcstr Pservicename, 4   _in_opt_  Const ADDRINFOA *phints,5   _out_     Paddrinfoa *  Ppresult6 );
getaddrinfo () function declaration

All two of these statements are deducted from MSDN. See the parameters of the getaddrinfo () function first, the macro before the parameter indicates that the first 3 parameters are incoming parameters, and the last one is the parameter that holds the output result.

The 1th parameter pnodename represents the hostname (or node name) or a string of numeric address strings, in short, the full name of the local computer, such as "lenovo-pc" or Baidu's domain name "www.baidu.com" Or a IPV4 address in dotted decimal notation or a IPV6 address in hexadecimal, as shown in the following example:

The 2nd parameter pservicename the service name or port number, service and port number one by one corresponding, service is for the application layer, and the following transport layer, network layer, link layer independent, commonly used services including HTTP, FTP, telnet, domain, etc., the corresponding relationship can be in the% Windir%\system32\drivers\etc\services See in this file

The

3rd parameter phints is a pointer to the ADDRINFOA type, and Addrinfoa is the alias of the struct addrinfo. About this parameter MSDN said a lot of Balabala, in short, this parameter is like a filter, by assigning values to struct members, the filter will filter out the data we need. Let's take a look at the addrinfo structure, the description of this structure MSDN gives a lot of Balabala, I just pick up I understand that the other interested can go to http://msdn.microsoft.com/en-us/library/windows/ desktop/ms738520 (v=vs.85). aspx look. The first parameter ai_flags I don't say much, MSDN about it's description super, see for yourself. The second parameter, ai_family, represents the protocol family, and af_inet means that IPV4;AF_INET6 represents Ipv6;af_netbios I don't know what it is, anyway, there is one, and it is not acceptable to Af_unspec and Pf_unspec. No agreement is accepted by the third party. The third parameter, Ai_socktype, represents the accepted data type, and 0 means that any type is accepted. You can see its macro definition in WinSock2.h

1 #define Sock_stream     1/               * STREAM socket */2#define sock_dgram      2               */Datagram Socket */3  #define sock_raw        3               */raw-protocol interface */4#define SOCK_RDM        4/               * reliably-delivered message */5#define sock_seqpacket  5/               * Sequenced Packet Stream */

The fourth parameter represents the supported transport-layer protocol type, and Ipproto_tcp accepts TCP,IPPROTO_UDP accept udp,0 expression. The following four parameters are used to store the returned address information.

The 4th parameter, Ppresult, is a pointer to the PADDRINFOA type, which is a double pointer of type Addrinfo. Used to store returned results. The address returned is often a list of two IP addresses 115.239.211.110 and 115.239.210.27 for a certain degree in the experiment above.

Get ready for knowledge, here's how to use the getaddrinfo () function to get the IP of a local host or remote domain name.

First initialize the Ws2_32.dll

1  Iresult = WSAStartup (Makeword (22), &wsadata); 2     if 0 ) {3         printf ("WSAStartup failed:%d\n", Iresult); 4         return 1 ; 5     }

Fill in the filter information into the hints

1     sizeof (hints)); 2     hints.ai_family = Af_unspec; 3     Hints.ai_socktype = sock_stream; 4     Hints.ai_protocol = ipproto_tcp;

Call the getaddrinfo () function to get the address information

 1  dwretval = getaddrinfo (Argv[1 ], Argv[2 ], &hints, &result);  2  if  (dwretval! = 0   3  printf ( " getaddrinfo failed with error:%d\n  "   4   WSACleanup ();  5  return  1   6 } 

Then there is the interesting part that interprets the return information.

In the case of IPV4, the returned IP address is stored in the member variable ai_addr of the Addrinfo struct, first to make a judgment, if IPV4, because the size of the struct sockaddr and the struct sockaddr_in is 14 bytes, Convert a struct sockaddr *ai_addr to a IPV4 address structure struct sockaddr_in *ai_addr with a forced type conversion. The Inet_ntoa () function is then called to convert the result to a dotted decimal representation of the IP address

1  Caseaf_inet:2printf"af_inet (IPv4) \ n");3Sockaddr_ipv4 = (structsockaddr_in *) ptr->ai_addr;4printf"\tipv4 Address%s\n",5Inet_ntoa (sockaddr_ipv4->sin_addr));6                  Break;

If it is IPV6, not in detail here, discussed later, directly on the code

1Sockaddr_ip = (lpsockaddr) ptr->ai_addr;2                 //The buffer length is changed by the wsaaddresstostring3                 //So we need to set it for each iteration through the loop for safety4Ipbufferlength = $;5iRetVal = Wsaaddresstostring (Sockaddr_ip, (DWORD) ptr->Ai_addrlen, NULL,6Ipstringbuffer, &ipbufferlength);7                 if(iRetVal)8printf"wsaaddresstostring failed with%u\n", WSAGetLastError ());9                 Else    Tenprintf"\tipv6 Address%s\n", Ipstringbuffer);


The full code is available on MSDN and is not posted here.

Winsock2 Study (a) the use of the getaddrinfo () function

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.