1、背景
在实际项目开发中,服务端有可能提供域名或者ip地址,在提供域名时,则需要通过域名获取到真实的ip地址。
同时考虑到代码的兼容性,因此代码需在linux和windows环境下均可运行。
2、demo
#include <iostream>
#include <string.h>
#include <string>
#if defined(__GNUC__)
#include <arpa/inet.h>
#include <resolv.h>
#include <netdb.h>
#elif defined(_MSC_VER)
#include <WinSock2.h>
#include <ws2tcpip.h>
#pragma comment(lib, "ws2_32.lib") // 连接库
#endif
int main()
{
const char* hostname = "www.ds.com";
#if defined(__GNUC__)
// 初始化一个hostent结构体用于存储DNS查询结果
struct hostent* result = gethostbyname(hostname);
if (result == nullptr)
{
return 1;
}
in_addr* addr_list = reinterpret_cast<in_addr*>(result->h_addr_list[0]);
char* ip = inet_ntoa(addr_list[0]);
std::string str_ip(ip, strlen(ip));
std::cout << "IP address: " << str_ip << std::endl;
#elif defined(_MSC_VER)
WSADATA wsaData;
WSAStartup(MAKEWORD(2, 2), &wsaData);
struct addrinfo hints, * res;
memset(&hints, 0, sizeof hints);
hints.ai_family = AF_INET; // ipv4
hints.ai_socktype = SOCK_STREAM;
if (getaddrinfo(hostname, NULL, &hints, &res) != 0)
{
std::cerr << "get addr info failed" << std::endl;
WSACleanup();
Sleep(3000);
return 1;
}
struct sockaddr_in* ipv4 = (struct sockaddr_in*)res->ai_addr;
char ipStr[INET_ADDRSTRLEN];
inet_ntop(AF_INET, &ipv4->sin_addr, ipStr, INET_ADDRSTRLEN);
std::cout << "IP address: " << ipStr << std::endl;
freeaddrinfo(res); // 释放getaddrinfo分配的资源
WSACleanup(); // 清理WSA环境
#endif
return 0;
}