// test1.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <Winsock2.h>
#include <ws2tcpip.h>
#include <iostream>
#include <string>
using namespace std;
#pragma comment(lib, "Ws2_32.lib")
/*********************************************
* 通过域名获取IP地址
* hostname : 域名地址 例:www.baidu.com
*********************************************/
string getIpByHostName(char *hostname)
{
struct hostent* hostAddr = gethostbyname(hostname);
if(hostAddr == NULL)
{
cout << "无法找到服务器主机" << endl;
return "";
}
//遍历别名
for(int i=0; hostAddr->h_aliases[i]; i++)
{
printf("Alias %d : %s\n", i+1, hostAddr->h_aliases[i]);
}
//地址类型
printf("Address type : %s\n", (hostAddr->h_addrtype==AF_INET) ? "AF_INET" : "AF_INET6");
//IP地址
char ipv4[100];
memset(ipv4, 0, 100);
if (hostAddr)
{
#if 1
int i1 = hostAddr->h_addr_list[0][0]&0x00ff;
int i2 = hostAddr->h_addr_list[0][1]&0x00ff;
int i3 = hostAddr->h_addr_list[0][2]&0x00ff;
int i4 = hostAddr->h_addr_list[0][3]&0x00ff;
sprintf_s(ipv4,"%d.%d.%d.%d",i1,i2,i3,i4);
#else
for(int i=0; hostAddr->h_addr_list[i]; i++)
{
//这里使用标准转换运算符reinterpret_cast,强制转换会出现警告
struct in_addr tmpAddr = *reinterpret_cast<struct in_addr*>(hostAddr->h_addr_list[i]);
char *ch = inet_ntoa(tmpAddr);
if (ch != NULL)
{
strcat(ipv4, ch);
}
}
#endif
}
return ipv4;
}
int _tmain(int argc, _TCHAR* argv[])
{
WSADATA wsaData;
WSAStartup(MAKEWORD(2,2), &wsaData);
char** pptr = NULL;
char szHostName[256] = {};
cout << "--------------------------------------" << endl;
cout << "输入域名:";
while( cin.getline( szHostName, sizeof(szHostName) ) )
{
//char *ip = new char;
string sIP;
sIP = getIpByHostName(szHostName);
cout << sIP << endl;
}
WSACleanup();
return 0;
}
通过域名获取IP地址 C/C++
最新推荐文章于 2025-04-11 10:02:10 发布
这个C++程序演示了如何使用Winsock库通过域名获取IP地址。它首先初始化Winsock,然后调用gethostbyname函数来解析域名。程序会显示服务器的别名、地址类型,并将IP地址以字符串形式返回。
453

被折叠的 条评论
为什么被折叠?



