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

}

相关推荐
lularible35 分钟前
PTP协议精讲(4.5):编译运行与测试
网络·网络协议·开源·嵌入式·ptp
Simon523141 小时前
HTTP、Cookie、Session知识小计
网络·网络协议·http
XS0301061 小时前
HTTP协议
网络·网络协议·http
不能隔夜的咖喱1 小时前
黑马ai大模型笔记(自用,比较粗糙)
linux·windows·python
jio本小子1 小时前
Windows 安装 Java17 + Maven + MySQL 开发环境教程,全程安装到 D 盘
windows·mysql·maven
暴力求解1 小时前
Linux--网络-->UDP_socket
linux·网络·网络协议·udp·操作系统
顶点多余1 小时前
传输层协议TCP详解----下
网络·网络协议·tcp/ip
想唱rap1 小时前
NAT、内网穿透、代理服务
java·linux·网络·网络协议·udp·智能路由器
H Journey1 小时前
TCP三次握手
网络协议·tcp/ip·三次握手
liulilittle2 小时前
TCP BBR调优及监控
linux·网络·网络协议·tcp/ip·win