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

}

相关推荐
hazy1k31 分钟前
ESP32基础-Socket通信 (TCP/UDP)
c语言·单片机·嵌入式硬件·网络协议·tcp/ip·udp·esp32
xinxinhenmeihao1 小时前
爬虫为什么要用动态ip?动态IP在爬虫中起到哪些作用?
爬虫·网络协议·tcp/ip
yanghuashuiyue3 小时前
windows vue3开发环境搭建
windows
特种加菲猫3 小时前
用户数据报协议(UDP)详解
网络·网络协议·udp
uestc_Venn3 小时前
Windows 11系统出现User Profile Service 服务登录失败。无法加载用户配置文件。 的解决办法
windows·电脑
cccyi73 小时前
HTTP 协议详解:从基础到核心特性
网络协议·http·应用层
lkbhua莱克瓦243 小时前
Java项目——斗地主小游戏(控制台版)
java·开发语言·windows·斗地主项目
渡我白衣4 小时前
五种IO模型与非阻塞IO
运维·服务器·网络·c++·网络协议·tcp/ip·信息与通信
重启的码农5 小时前
enet源码解析(7): 跨平台套接字调用抽象层
c++·网络协议
tan180°5 小时前
Linux网络TCP(中)(12)
linux·网络·后端·tcp/ip