#include <iostream>
using namespace std;
#define _WINSOCK_DEPRECATED_NO_WARNINGS
#include <WinSock2.h>
#pragma comment(lib,"WS2_32.lib")class CInitSock
{
public:CInitSock(){//必须要注册网络库WSADATA wsd;if (::WSAStartup(MAKEWORD(2, 2), &wsd) != 0){exit(0);}}~CInitSock(){::WSACleanup();}
};//获取本地所有的iP地址
void fun1()
{CInitSock inits;//1.获取主机名char bufname[256] = {0};::gethostname(bufname, 256);printf("%s\n",bufname);//2.得到地址信息hostent* pHost = ::gethostbyname(bufname);in_addr addr;for (int i = 0;;i++){char* p = pHost->h_addr_list[i];if (p == nullptr){break;}memcpy(&addr.S_un.S_addr, p, pHost->h_length);char* szIP = inet_ntoa(addr);printf("本机IP地址:%s\n",szIP);}
}//域名解析
void fun2()
{CInitSock inits;//1.获取主机名char hostname[256] = { 0 };printf("请输入解析的域名:");cin>>hostname;//www.baidu.com//2.得到地址信息hostent* pHost = ::gethostbyname(hostname);in_addr addr;for (int i = 0;; i++){char* p = pHost->h_addr_list[i];if (p == nullptr){break;}memcpy(&addr.S_un.S_addr, p, pHost->h_length);char* szIP = inet_ntoa(addr);printf("域名:%s IP地址:%s\n", hostname, szIP);printf("服务器名字:%s\n",pHost->h_name);}
}
int main()
{ cout << "*******************\n";fun1();cout << "*******************\n";cout << "*******************\n";fun2();cout << "*******************\n";system("pause");return 0;}
结果: