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

}

相关推荐
Oflycomm16 分钟前
工业以太网四大主流协议(EtherCAT/PROFINET/EtherNet/IP/Modbus)技术参数深度对比
网络·网络协议·tcp/ip·欧飞信·plc模组
wangl_922 小时前
Modbus RTU 与 Modbus TCP 深入指南-现代替代协议
网络·网络协议·tcp/ip·tcp·modbus·rtu
Andy4 小时前
C++ list容器基本逻辑结构详解
c++·windows·list
霸道流氓气质4 小时前
SpringAIAlibaba整合 Streamable HTTP 调用免费 MCP Server 实战全解
网络·网络协议·http
想唱rap5 小时前
传输层协议TCP
linux·运维·服务器·网络·c++·tcp/ip
一只小白0006 小时前
一篇讲清TCP的三次握手&四次挥手
服务器·网络·tcp/ip
上海云盾-小余7 小时前
网站木马植入原理与彻底清除、长效防御方案
网络·网络协议·tcp/ip·系统安全
扬帆破浪7 小时前
免费开源AI软件.桌面单机版,可移动的AI知识库,察元 AI桌面版:免费开源的AI软件首启动 FirstRunSetup向导背后做了什么
人工智能·windows·电脑·知识图谱
ITHAOGE157 小时前
2026年Win7最终版ISO系统映像下载!(集成补丁、旗舰版、完整无精简、64位/32位可选、Windows 7、简体中文/繁体中文/英语可选)
windows·科技·microsoft·微软·电脑
yuanpan7 小时前
Python + PyAutoGUI 实战:Windows 自动化办公脚本开发入门
windows·python·自动化