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

}

相关推荐
ZhengEnCi18 分钟前
Q0-网络请求是什么?API?🌐
网络协议
怀旧,31 分钟前
【Linux网络编程】3. Socket编程 TCP
linux·网络·tcp/ip
享乐主34 分钟前
DHCP - Dynamic Host Configuration Protocol
网络协议·dhcp
上海云盾-小余38 分钟前
服务器频繁遭暴力攻击?IP 更换、防护加固一站式解决方案
运维·服务器·tcp/ip
wuyoula43 分钟前
如何在捷云鲸论坛高效获取高质量技术解答?
服务器·c++·人工智能·tcp/ip·源码
Shota Kishi1 小时前
深入解析 Solana RPC getTransaction 性能优化:以最近 30 个 epoch 为重点的历史交易检索提速实践
网络协议·性能优化·rpc
beyond阿亮1 小时前
Hermes Agent 在Windows上接入飞书完整指南
人工智能·windows·ai·hermes agent
葱卤山猪1 小时前
【自用】解析http post表单数据,将其中的二进制数据保存到csv文件且加载到内存
网络·网络协议·http
ba_pi1 小时前
windows Claude Code接入deepseek,全局配置
windows·claude·deepseek
stanleyrain1 小时前
Windows 实现 Linux 风格“选中即复制,中键即粘贴”操作指南
linux·运维·windows