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

}

相关推荐
Bruce_Liuxiaowei9 分钟前
Windows系统错误6118全面解决方案:修复此工作组的服务器列表当前无法使用
运维·服务器·windows·网络安全
我有一颗五叶草36 分钟前
HTTP 协议
网络·网络协议·http
沐风ya1 小时前
RPC介绍
网络·网络协议·rpc
水饺编程2 小时前
第3章,[标签 Win32] :窗口类03,窗口过程函数字段
c语言·c++·windows·visual studio
一苓二肆2 小时前
代码加密技术
linux·windows·python·spring·eclipse
LinXunFeng2 小时前
如何舒适地沉浸式编程,这是我的答案
windows·程序员·mac
G31135422732 小时前
云服务器怎么设置虚拟IP,云服务器能起虚拟ip吗
运维·服务器·tcp/ip
9527出列3 小时前
Netty源码分析--客户端连接接入流程解析
网络协议·netty
初听于你4 小时前
深入了解—揭秘计算机底层奥秘
windows·tcp/ip·计算机网络·面试·架构·电脑·vim
Ching·4 小时前
linux系统编程(十③)RK3568 socket之 TCP 服务器的实现【更新客户端断开重连依旧可以收发】
linux·服务器·tcp/ip·rk3568