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

}

相关推荐
其实防守也摸鱼13 小时前
GDB安装与配置(保姆级教程)【Linux、Windows系统】
linux·运维·windows·命令模式·工具·虚拟机·调试
Hello_Embed21 小时前
嵌入式上位机开发入门(二十六):将 MQTT 测试程序加入 APP 任务
网络·笔记·网络协议·tcp/ip·嵌入式
武藤一雄21 小时前
19个核心算法(C#版)
数据结构·windows·算法·c#·排序算法·.net·.netcore
pengyi8710151 天前
动态IP池快速更换实操方案,5分钟完成IP替换
服务器·网络·tcp/ip
淼淼爱喝水1 天前
ESXi 给 Windows Server 2008 虚拟机添加磁盘教程
windows·esxi·虚拟机
勤自省1 天前
《RDK X5 ROS 2 Humble 安装与验证:从零到 Hello World》
windows·ubuntu·ssh·ros2
docsz1 天前
Windows开发环境配置
windows
eggwyw1 天前
PHP搭建开发环境(Windows系统)
开发语言·windows·php
IpdataCloud1 天前
IP查询高精度怎么选?8个指标判断是否适合你
网络·网络协议·tcp/ip
聊点儿技术1 天前
IP风险等级评估是什么?跨境电商业务场景全解析
网络·网络协议·tcp/ip