#include <winsock2.h>
#pragma comment(lib,"ws2_32.lib")
#include <iostream.h>
void main()
{
//获取主机名称
WSAData wsaData;
if(WSAStartup(MAKEWORD(1, 1), &wsaData))
{
cout<<WSAGetLastError()<<endl;
}
char host_name[255];
int j = gethostname(host_name, sizeof(host_name));
if(j!=0)
{
cout<<WSAGetLastError()<<endl;
}
else
{
cout<<"主机名称为:"<<host_name<<endl;
}
//获取主机IP地址
struct hostent *phe = gethostbyname(host_name);
if (phe == 0)
{
cout<<"Yow! Bad host lookup."<<endl;
}
for (int i = 0; phe->h_addr_list[i] != 0; ++i)
{
struct in_addr addr;
memcpy(&addr, phe->h_addr_list[i], sizeof(struct in_addr));
cout<<"第"<<i<<"个IP为:"<<inet_ntoa(addr)<<endl;
}
WSACleanup();
//system("pause");
}
C++获得主机IP地址
最新推荐文章于 2019-05-05 16:11:34 发布