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

}

相关推荐
Jony_3 小时前
高可用移动网络连接
网络协议
chilix8 小时前
Linux 跨网段路由转发配置
网络协议
埃博拉酱1 天前
VS Code Remote SSH 连接 Windows 服务器卡在"下载 VS Code 服务器":prcdn DNS 解析失败的诊断与 BITS 断点续传
windows·ssh·visual studio code
唐宋元明清21882 天前
.NET 本地Db数据库-技术方案选型
windows·c#
加号32 天前
windows系统下mysql多源数据库同步部署
数据库·windows·mysql
tryCbest2 天前
Windows环境下配置pip镜像源
windows·pip
呉師傅2 天前
火狐浏览器报错配置文件缺失如何解决#操作技巧#
运维·网络·windows·电脑
gihigo19982 天前
基于TCP协议实现视频采集与通信
网络协议·tcp/ip·音视频
百事牛科技2 天前
保护文档安全:PDF限制功能详解与实操
windows·pdf
一个人旅程~2 天前
如何用命令行把win10/win11设置为长期暂停更新?
linux·windows·经验分享·电脑