getaddrinfo函数用法示例

getaddrinfo函数用法示例

上篇文章介绍了getaddrinfo替代gethostbyname 由域名获取IP的情况,本篇文章详细介绍getaddrinfo的用法

其用法简单使用演示如下。windows下包含头文件#include <ws2tcpip.h>,Linux包含头文件#include<netdb.h>。另外最重要的是hints参数的设置,详细参数说明可以参照百度百科,MSDN等等。

[cpp]#include “stdafx.h”

#include
#include
#include

#pragma comment (lib, “Ws2_32.lib”)

int main(int argc, char **argv)
{
WORD wVersion;
WSADATA WSAData;
wVersion=MAKEWORD(2,2);
WSAStartup(wVersion,&WSAData);
struct addrinfo hints;
struct addrinfo *res, *cur;
int ret;
struct sockaddr_in *addr;
char m_ipaddr[16];

memset(&hints, 0, sizeof(struct addrinfo));
hints.ai_family = AF_INET; /* Allow IPv4 */
hints.ai_flags = AI_PASSIVE;/* For wildcard IP address */
hints.ai_protocol = 0; /* Any protocol */
hints.ai_socktype = SOCK_STREAM;

ret = getaddrinfo(“cpp.cloudcpp.com”, NULL,&hints,&res);

if (ret == -1) {
perror(“getaddrinfo”);
exit(1);
}
for (cur = res; cur != NULL; cur = cur->ai_next) {
addr = (struct sockaddr_in *)cur->ai_addr;
sprintf(m_ipaddr, “%d.%d.%d.%d”,
(*addr).sin_addr.S_un.S_un_b.s_b1,
(*addr).sin_addr.S_un.S_un_b.s_b2,
(*addr).sin_addr.S_un.S_un_b.s_b3,
(*addr).sin_addr.S_un.S_un_b.s_b4);
printf(“%s\n”,m_ipaddr);
}
freeaddrinfo(res);
return 0;
}[/cpp]

百度IP获取如下所示,当然也可以获取cpp.cloudcpp.com的IP地址信息。

getaddrinfo
getaddrinfo