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

}

相关推荐
❆VE❆11 分钟前
Claude Code 安装与配置完整指南(Windows)
windows·claude code
汤愈韬26 分钟前
网络安全之网络基础知识_2
网络协议·安全·web安全
航Hang*44 分钟前
VMware vSphere 云平台运维与管理基础——第5章:VMware vSphere 5.5 高级特性
运维·服务器·开发语言·windows·学习·虚拟化
Mapleay1 小时前
Ubuntu 源的重要性!之 libgmp-dev 无法安装
linux·服务器·windows
humors2211 小时前
微软工具包下载网址
windows·microsoft·微软·office·工具包·sysintervals
王燕龙(大卫)1 小时前
tcp报文什么时候会真正发送
服务器·网络·tcp/ip
寺中人1 小时前
硬盘提示初始化的损坏,手动恢复MBR及EBR分区教程
windows·工具·硬盘修复
冷色系里的一抹暖调2 小时前
OpenClaw Docker 部署避坑指南:服务启动成功但网页打不开?
人工智能·windows·docker·ai·容器·opencode
开开心心就好2 小时前
能把网页藏在Word里的实用摸鱼工具
linux·运维·服务器·windows·随机森林·逻辑回归·excel
Bruce_Liuxiaowei2 小时前
技嘉Aorus主板Win10引导故障深度修复:从网络重置到注册表移植
服务器·网络·windows·microsoft