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

}

相关推荐
Json_26 分钟前
springboot框架对接物联网,配置TCP协议依赖,与设备通信,让TCP变的如此简单
java·后端·tcp/ip
Angletank35 分钟前
SpringBoot用JPA接口实现分页和排序
windows·spring boot·后端
刺客xs2 小时前
TCP网络通信
网络·网络协议·tcp/ip
爬山算法3 小时前
Netty(26)如何实现基于Netty的RPC框架?
网络·网络协议·rpc
JIes__4 小时前
网络协议——网络层协议
网络协议
网安INF4 小时前
SSL/TLS体系结构
网络·网络协议·网络安全·ssl
不染尘.4 小时前
TCP客户服务器编程模型
linux·服务器·网络·网络协议·tcp/ip·计算机网络·ssh
JIes__4 小时前
网络协议——数据链路层协议
网络协议
may_一一5 小时前
appium安装(windows)
windows·appium
曾几何时`5 小时前
网络协议(五)数据链路层 ARP协议
网络·网络协议