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

}

相关推荐
扑火的小飞蛾14 分钟前
Windows 10 与 Kali Linux SSH 免密互信配置指南
linux·windows·ssh
MOYIXIAOWEIWEI22 分钟前
VMware-centos7更改静态ip
网络·网络协议·tcp/ip
Chris _data1 小时前
从宿主机(Windows)通过 NAT 模式连接虚拟机(Ubuntu)中的 MySQL
windows·mysql·ubuntu
Strange_Head2 小时前
《Linux系统网络协议》从 TCP 到 HTTP:理解 Web 通信的第一步——网络篇
linux·网络·网络协议
爱吃生蚝的于勒2 小时前
【Linux】重中之重!TCP协议
linux·运维·服务器·网络·学习·tcp/ip
楼田莉子2 小时前
Linux网络:TCP协议
linux·运维·服务器·网络·tcp/ip
杨云龙UP2 小时前
Oracle 19c:RMAN Duplicate异机复制数据库实操_20260402
linux·运维·服务器·数据库·网络协议·tcp/ip·oracle
高兴就好20482 小时前
ClaudeCode在windows 11安装方法(2026年4月)
windows
公子小六2 小时前
基于.NET的Windows窗体编程之WinForms布局简介
windows·microsoft·c#·.net
Flamingˢ2 小时前
YNQ + OV5640 视频系统开发(二):OV5640_Data IP 核源码解析
arm开发·嵌入式硬件·网络协议·tcp/ip·fpga开发·vim·音视频