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

}

相关推荐
热爱生活的五柒1 小时前
WebDAV如何使用?
windows
路由侠内网穿透.1 小时前
本地部署智能家居集成解决方案 ESPHome 并实现外部访问( Linux 版本)
linux·运维·服务器·网络协议·智能家居
吠品1 小时前
什么是 IP SSL 证书?该如何申请
网络协议·tcp/ip·ssl
奋斗羊羊2 小时前
TCP、UDP 和串口通信对比分析
网络协议·tcp/ip·udp
面对疾风叭!哈撒给3 小时前
Windows 系统使用NSSM创建 Windows服务
windows
MyBFuture3 小时前
C#数组详解:一维二维与交错数组
开发语言·windows·c#·visual studio·vision pro
生活很暖很治愈3 小时前
GUI自动化测试[3]——控件&数鼠标操作
windows·python·功能测试·测试工具
HAPPY酷4 小时前
构建即自由:一份为创造者设计的 Windows C++ 自动化构建指南
开发语言·c++·ide·windows·python·策略模式·visual studio
忘忧记4 小时前
某小说数据分析过程
windows·数据挖掘·数据分析
PPPPPaPeR.4 小时前
环 境 变 量
linux·运维·windows