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

}

相关推荐
liulun1 小时前
C++ WinRT中的异步
c++·windows
xyty33203 小时前
QImageReader 的全局静态锁原理
c++·windows·qt
Bruce_Liuxiaowei3 小时前
深入剖析 Windows 网络服务:用 witr 一键溯源所有监听端口
windows·安全·系统安全
白太岁5 小时前
Muduo:(3) 线程的封装,线程 ID 的获取、分支预测优化与信号量同步
c++·网络协议·架构·tcp
overmind6 小时前
oeasy Python 116 用列表乱序shuffle来洗牌抓拍玩升级拖拉机
服务器·windows·python
独自破碎E6 小时前
Windows 环境下 OpenClaw 的安装与千问大模型配置
windows
开开心心就好7 小时前
实用系统备份还原,小巧免PE备份快镜像小
windows·计算机视觉·pdf·计算机外设·迭代器模式·excel·桥接模式
Bruce_Liuxiaowei7 小时前
Windows 进程溯源工具 witr:原理、安装与实战
windows·网络安全
cjl_8520088 小时前
MySQL-递归查询
数据库·windows·mysql
白太岁8 小时前
Muduo:(2) EPollPoller 实现 epoll 封装、 fd 事件监听与事件通知
网络·c++·网络协议·tcp/ip