#include <winsock2.h>
#include <iostream>
using namespace std;
#pragma comment(lib, "WS2_32.lib")
void getIP()
{
WSADATA WSAData; //WSADATA結構被用來儲存調用AfxSocketInit全局函數返回的Windows Sockets初始化信息。
if (WSAStartup(MAKEWORD(2, 0),&WSAData)) // 初始化Windows sockets API
{
printf("WSAStartup failed %s\n", WSAGetLastError());
exit(-1); //異常退出
}
char hostName[256];
if(gethostname(hostName,sizeof(hostName))) //獲取主機名
{
printf("Error: %u\n", WSAGetLastError());
exit(-1);
}
hostent *host=gethostbyname(hostName); // 根據主機名獲取主機信息(含IP)
if(host==NULL)
{
printf("Error: %u\n", WSAGetLastError());
exit(-1);
}
cout<<"正式的主機名: "<<host->h_name<<endl
<<"主機地址類型: "<<host->h_addrtype<<endl
<<"地址清單: "<<host->h_addr_list<<endl
<<"别名列表: "<<host->h_aliases<<endl
<<"地址長度: "<<host->h_length<<endl;
for(int i=0;host->h_addr_list[i]!=0;i )
{
cout<<"該主機IP"<<i 1<<": "<<inet_ntoa(*(struct in_addr*)*host->h_addr_list)<<endl;
}
WSACleanup();
}
int main()
{
getIP();
system("pause");
return 0;
}
,
更多精彩资讯请关注tft每日頭條,我们将持续为您更新最新资讯!