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 天前
Dubbo配置方式大全:七种配置任你选,轻松玩转微服务!
服务器·网络·网络协议·微服务·云原生·架构·dubbo
liulilittle1 天前
C++ 并发双阶段队列设计原理与实现
linux·开发语言·c++·windows·算法·线程·并发
xinxinhenmeihao1 天前
爬虫如何使用代理IP才能不被封号?有什么解决方案?
爬虫·网络协议·tcp/ip
悦悦子a啊1 天前
[Java]实验--编写TCP客户端程序
java·tcp/ip·php
Moonquake_www1 天前
WSL2设置桥接网络至主机IP
网络·网络协议·tcp/ip
wuletaotao1 天前
Windows 下 Redis 使用完整教程
数据库·windows·redis
苏小瀚1 天前
[JavaSE] 网络原理(HTTP_HTTPS)
网络·tcp/ip·http
杜大哥1 天前
电脑:如何解决电脑网络IP地址冲突?
网络协议·tcp/ip·电脑
cui_win1 天前
HTTP协议:常见状态码(400/500 系列)
网络·网络协议·http
渡我白衣1 天前
并行的野心与现实——彻底拆解 C++ 标准并行算法(<execution>)的模型、陷阱与性能真相
java·开发语言·网络·c++·人工智能·windows·vscode