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

}

相关推荐
草履虫建模4 小时前
Java 集合框架:接口体系、常用实现、底层结构与选型(含线程安全)
java·数据结构·windows·安全·决策树·kafka·哈希算法
qq_24218863325 小时前
快速搭建跨环境检测服务的步骤
linux·开发语言·windows·python·macos
呉師傅5 小时前
【操作技巧】Win10关机提示这个应用阻止关机。怎么解决?
运维·网络·windows·电脑
FL16238631295 小时前
windows从源码安装python版本paddleocr3.4.0
开发语言·windows·python
航哥的女人7 小时前
setsockopt()详解
c++·tcp/ip
天荒地老笑话么7 小时前
Bridged 下 IP 冲突:冲突识别与修复
网络·网络协议·tcp/ip
航哥的女人7 小时前
基于TCP的socket编程
网络·网络协议·tcp/ip
x***r1518 小时前
TUPortable安装步骤详解(附流量监控与进程占用查看教程)
windows
WrkZmkvJ9 小时前
博世汽车电驱仿真Simulink 模型, 同步电机和异步电机模型, 相电流完美波形 MPTA+...
tcp/ip
Zzz 小生10 小时前
LangChain Messages:消息使用完全指南
数据库·windows·microsoft