转自:C++获取本地计算机主机名和IP
#include <iostream>
#include "winsock2.h"
using namespace std;
#pragma comment(lib,"ws2_32.lib")
void main()
{
WSAData data;
if(WSAStartup(MAKEWORD(1, 1), &data) != 0){
cout << "初始化错误,无法获取主机信息..." << endl;
}
char host[255];
if(gethostname(host, sizeof(host)) == SOCKET_ERROR){
cout << "无法获取主机名..." << endl;
}
else{
cout << "本机计算机名为:" << host << endl;
}
struct hostent *p = gethostbyname(host);
if(p == 0){
cout << "无法获取计算机主机名及IP..." << endl;
}
else{
for(int i = 0; p->h_addr_list[i] != 0; i++){
struct in_addr in;
memcpy(&in, p->h_addr_list[i], sizeof(struct in_addr));
cout << "第" << i + 1 << "块网卡的IP为:" << inet_ntoa(in) << endl;
}
}
WSACleanup();
cin.get();
}