Checks the local names and IP addresses
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++;
}
Resolve domain names and IP address of the host computer output
//解析域名
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++;
}
All codes
#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;
}