参考文章:http://www.cnblogs.com/cxz2009/archive/2010/11/19/1881693.html
运行环境: Win10 Professional , Visual Studio 2015
测试代码:
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <WinSock2.h>
#include <WS2tcpip.h>
using namespace std;
#pragma comment(lib,"ws2_32.lib")
int main(int argc, char *argv[])
{
//初始化环境
WSADATA ws;
WSAStartup(MAKEWORD(2, 2), &ws);
struct addrinfo hints;
struct addrinfo *res, *cur;
struct sockaddr_in *addr;
// 保存Ip地址信息 xxx.xxx.xxx.xxx
char m_IpAddr[16];
//初始化 hints
memset(&hints, 0, sizeof(addrinfo));
hints.ai_family = AF_INET; //IPv4
hints.ai_flags = AI_PASSIVE; //匹配所有 IP 地址
hints.ai_protocol = 0; //匹配所有协议
hints.ai_socktype = SOCK_STREAM; //流类型
//获取 ip address , res 指向一个链表Address Information链表
int ret = getaddrinfo("www.baidu.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; //获取当前 address
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); //输出到控制台
}
//清除环境信息
WSACleanup();
system("pause");
return 0;
}
参考运行结果:
61.135.169.121
61.135.169.125
请按任意键继续. . .