1、簡潔版:
#include<winsock2.h>
#include<iostream>
#include<string>
using namespace std;
#pragma comment(lib, "WS2_32.lib")
string getIP()
{
WSADATA WSAData;
char hostName[256];
if (!WSAStartup(MAKEWORD(2, 0),&WSAData))
{
if(!gethostname(hostName,sizeof(hostName)))
{
hostent *host=gethostbyname(hostName);
if(host!=NULL)
{
return inet_ntoa(*(struct in_addr*)*host->h_addr_list);
}
}
}
return "Get IP failed.";
}
int main()
{
cout<<"IP地址爲:"<<getIP()<<endl;
system("pause");
return 0;
}
2、擴展板:
#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;
}