查詢本機名字與IP地址
struct hostent *hptr;
char **pptr;
char hostname[256];
//獲取主機名字
if (gethostname(hostname, sizeof(hostname))) {
cout << "獲取主機名字失敗!\n";
WSACleanup();
return 0;
}
cout << "hostname:" << hostname << endl;
//獲取本機IP地址
if ((hptr = gethostbyname(hostname)) == NULL) {
cout << "通過主機名獲取本機IP地址失敗!n" << endl;
WSACleanup();
return 0;
}
pptr = hptr->h_addr_list;
cout << "host_ip:" << endl;
while (*pptr != NULL) {
//inet_ntoa:將一個包含在in_addr結構變量中的長整型IP地址轉換爲點分十進制形式
cout << inet_ntoa(*(struct in_addr *)(*pptr)) << endl; pptr++;
}
解析域名並輸出主機IP地址
//解析域名
cout << "輸入要解析的域名:" << endl;
cin >> hostname;
if ((hptr = gethostbyname(hostname)) == NULL) {
cout << "域名解析失敗!\n" << endl;
WSACleanup();
return 0;
}
//輸出遠程機器IP地址
pptr = hptr->h_addr_list;
cout << "ip:" << endl;
while (*pptr != NULL) {
cout << inet_ntoa(*(struct in_addr *)(*pptr)) << endl; pptr++;
}
全部代碼
#define _WINSOCK_DEPRECATED_NO_WARNINGS
#include "WinSock2.h"
#include "iostream"
#pragma comment(lib,"ws2_32.lib") //鏈接WinSock導入庫
using namespace std;
int main(int argc, char **argv) {
WSADATA wsaData;
WORD wVersionRequested = MAKEWORD(2, 2); //調用2.2版本
if (WSAStartup(wVersionRequested, &wsaData) != 0) { //加載WinSock動態鏈接庫
cout << "加載WinSock DLL失敗!\n";
return 0;
}
struct hostent *hptr;
char **pptr;
char hostname[256];
//獲取主機名字
if (gethostname(hostname, sizeof(hostname))) {
cout << "獲取主機名字失敗!\n";
WSACleanup();
return 0;
}
cout << "hostname:" << hostname << endl;
//獲取本機IP地址
if ((hptr = gethostbyname(hostname)) == NULL) {
cout << "通過主機名獲取本機IP地址失敗!n" << endl;
WSACleanup();
return 0;
}
pptr = hptr->h_addr_list;
cout << "host_ip:" << endl;
while (*pptr != NULL) {
//inet_ntoa:將一個包含在in_addr結構變量中的長整型IP地址轉換爲點分十進制形式
cout << inet_ntoa(*(struct in_addr *)(*pptr)) << endl; pptr++;
}
//解析域名
cout << "輸入要解析的域名:" << endl;
cin >> hostname;
if ((hptr = gethostbyname(hostname)) == NULL) {
cout << "域名解析失敗!\n" << endl;
WSACleanup();
return 0;
}
//輸出遠程機器IP地址
pptr = hptr->h_addr_list;
cout << "ip:" << endl;
while (*pptr != NULL) {
cout << inet_ntoa(*(struct in_addr *)(*pptr)) << endl; pptr++;
}
WSACleanup();
return 0;
}