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

}

相关推荐
Byron Loong3 小时前
【调试】Dump 文件分析的完整流程
windows
Geoking.5 小时前
VSCode 安装 Claude Code 插件 + ccswitch 配置 DeepSeek API 完整教程(Windows 新手向)
ide·windows·vscode
潘达斯奈基~5 小时前
Windows 下 Claude Code使用 Agent Teams 配置教程
windows
hellojackjiang20116 小时前
socket长连接在手游场景下的技术实践
网络·网络协议·tcp/ip·架构·网络编程
源远流长jerry6 小时前
Linux 本机网络通信机制深度解析:Loopback 设备原理
linux·运维·服务器·网络·tcp/ip·nginx·负载均衡
wangl_926 小时前
Modbus RTU 与 Modbus TCP 深入指南-安全加固方案
网络·网络协议·tcp/ip·安全·tcp·modbus·rtu
源远流长jerry7 小时前
Linux 网络性能优化:从应用到内核
linux·运维·服务器·网络·网络协议·性能优化
落叶_Jim7 小时前
Let‘s Encrypt证书有效期缩短至90天后,如何实现自动续期
网络协议·https·ssl
顶点多余8 小时前
自定义协议、序列化、反序列化实现
java·linux·开发语言·c++·tcp/ip
浪客灿心8 小时前
Linux网络IP协议
linux·网络·tcp/ip