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

}

相关推荐
破刺不会编程2 小时前
socket编程TCP
linux·运维·服务器·开发语言·网络·网络协议·tcp/ip
gxh19922 小时前
4步将HTTP请求升级为HTTPS
运维·服务器·网络协议·http·https
BullSmall2 小时前
日志打印IP:安全与合规的最佳实践
网络·tcp/ip·安全
李洛克074 小时前
RDMA CM UDP 通信完整指南
单片机·网络协议·udp
福尔摩斯张4 小时前
基于C++的UDP网络通信系统设计与实现
linux·c语言·开发语言·网络·c++·tcp/ip·udp
老王头的笔记5 小时前
Spring支持的消费器模式,支持在当前事务提交、或回滚的前、后执行业务操作
java·windows·spring
北京耐用通信5 小时前
终结混合网络调试噩梦:耐达讯自动化实现EtherCAT对DeviceNet设备的直接读写
网络·人工智能·物联网·网络协议·自动化·信息与通信
分***86 小时前
新版局域网IP扫描神器IPScanner.exe 绿色版V1.28.2,支持跨网段扫描_端口扫描_系统端口查看工具
网络·tcp/ip·端口扫描·ipscanner·局域网扫描
千天夜6 小时前
文件系统磁盘块分配方式:从隐式链接到索引结构
网络·网络协议
2501_915918416 小时前
HTTPS 端口深度解析,443 并不是唯一入口,理解 TLS 流量行为与抓包策略
网络协议·http·ios·小程序·https·uni-app·iphone