Windows c++获取本地ip

int GetLocalIp(vector<string> &vIp)

{

WSADATA wsaData;

int iRet = WSAStartup(((2 << 8) & 0xffff) | (2 & 0xff), &wsaData);

if (iRet != 0) {

std::cerr << "WSAStartup failed: " << iRet << std::endl;

return 1;

}

// 获取本机名

char hostname[256];

int result = gethostname(hostname, sizeof(hostname));

if (result != 0) {

std::cerr << "gethostname failed: " << WSAGetLastError() << std::endl;

WSACleanup();

return 1;

}

// 获取主机信息

struct hostent* phe = gethostbyname(hostname);

if (phe == nullptr) {

std::cerr << "gethostbyname failed: " << WSAGetLastError() << std::endl;

WSACleanup();

return 1;

}

// 遍历所有的IP地址

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));

vIp.push_back(inet_ntoa(addr));

std::cout << "Local IP " << i + 1 << ": " << inet_ntoa(addr) << std::endl;

}

WSACleanup();

}

相关推荐
胡八一2 小时前
Windows 7 运行 .NET 应用时报错“hostfxr.dll 加载失败 (HRESULT: 0x80070057)”的彻底解决指南
windows·.net
罗小爬EX4 小时前
基于WebSocket + STOMP + SockJS + RabbitMq的聊天室Demo
websocket·网络协议·rabbitmq
q***06294 小时前
如何在 Windows 上安装 MySQL(保姆级教程2024版)
数据库·windows·mysql
在路上看风景4 小时前
3.8 TCP面向字节流
网络·tcp/ip
初听于你5 小时前
深入解析IP, ICMP, OSPF, BGP四大核心网络协议
服务器·网络·网络协议·计算机网络·信息与通信·信号处理
还下着雨ZG14 小时前
TCP/IP协议族详细介绍
网络·网络协议·tcp/ip·计算机网络
耿直小伙14 小时前
电脑已连接网络无线自动重启
windows
m0_5656111315 小时前
Java-泛型
java·windows
蓁蓁啊16 小时前
Ubuntu 虚拟机文件传输到 Windows的一种好玩的办法
linux·运维·windows·单片机·ubuntu
serve the people17 小时前
Comma-Separated List Output Parser in LangChain
windows·langchain·list