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

}

相关推荐
wj319321 分钟前
ping一个ip打印无法访问目的主机一次,然后打印请求超时问题定位过程
服务器·网络·嵌入式硬件·网络协议·tcp/ip·局域网网内
曹自标29 分钟前
workflow 拓扑排序算法
windows·算法·排序算法
BIBI204933 分钟前
通过 HeidiSQL 连接 CentOS 7 中的 MySQL 5.7
linux·windows·mysql·centos·数据库管理·环境搭建·服务器运维
西柚补习生34 分钟前
TCP/IP和UDP的定义,区别,应用场景
网络·tcp/ip·udp
code_li39 分钟前
P2P加速 vs. CDN加速
网络·网络协议·p2p
RisunJan1 小时前
Linux命令-ip命令(网络配置工具)
linux·网络·tcp/ip
越甲八千1 小时前
windows调用C++动态库BOOL未定义
c++·windows·单片机
阿巴~阿巴~1 小时前
路由的本质:从逐跳转发到全球互联的决策机制解析
网络·网络协议·tcp/ip·智能路由器·ip·tcp·路由
赱向远方1 小时前
【Install MongoDB on windows】
数据库·windows·mongodb·安装·install
不染尘.1 小时前
线程编程模型和进程间通信概述
linux·windows·vscode·ssh·信息与通信