#include"pch.h"
#include <iostream>
#include <WinSock2.h> //包含WinSock库头文件
#include <ws2tcpip.h>
#pragma comment(lib,"WS2_32") //链接WinSock导入库
using namespace std;
int main(int argc, char** argv)
{
//初始化Winsock DLL (动态链接库)
WSADATA wsaData;
int ret;
if ((ret = WSAStartup(MAKEWORD(2, 2), &wsaData)) != 0)
{
std::cout << "初始化WinSock出错!";
return -1;
}
char hostname[256]; //用于存放获取的本机名称
if (gethostname(hostname, sizeof(hostname)))
{
cout << "获取主机名字失败!\n" << endl;
WSACleanup();
return 0;
}
cout << "主机名称:" << hostname << endl;
//根据主机名字查询主机的IPv4地址
struct addrinfo hints, * p_addrinfo, * p;
memset(&hints, 0, sizeof(hints));
hints.ai_family = AF_INET; //指定只查询IPv4地址
unsigned int retval = getaddrinfo(hostname, NULL, &hints, &p_addrinfo);
if (retval != 0) {
printf("getaddrinfo failed with error: %d\n", retval);
WSACleanup();
return 1;
}
//输出IP地址
p = p_addrinfo;
cout << "本机IP地址:" << endl;
char ipaddr[20];
in_addr addr;
while (p != NULL)
{
addr = ((sockaddr_in*)(p->ai_addr))->sin_addr;
cout << inet_ntop(AF_INET, (void*)&addr, ipaddr, 20) << endl;
p = p->ai_next;
}
}