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

}

相关推荐
自由鬼几秒前
Apache HTTP Server 2.4.49 的目录遍历漏洞CVE-2021-41773
网络协议·http·apache
van叶~6 分钟前
Linux网络-------1.socket编程基础---(TCP-socket)
linux·网络·tcp/ip
极地星光1 小时前
TCP/IP 网络编程面试题及解答
网络·网络协议·tcp/ip
Lucky高3 小时前
HTTP和HTTPS复习
网络协议·http·https
吳所畏惧3 小时前
NVM踩坑实录:配置了npm的阿里云cdn之后,下载nodejs老版本(如:12.18.4)时,报404异常,下载失败的问题解决
前端·windows·阿里云·npm·node.js·batch命令
leese2333 小时前
FreeMarker模板引擎
windows
love530love4 小时前
命令行创建 UV 环境及本地化实战演示—— 基于《Python 多版本与开发环境治理架构设计》的最佳实践
开发语言·人工智能·windows·python·conda·uv
呉師傅5 小时前
佳能iR-ADV C5560复印机如何扫描文件到电脑
运维·网络·windows·计算机外设·电脑
程序视点5 小时前
【最新专业评测】PDF Reducer专业版:85%超高压缩率的PDF压缩神器|Windows最佳PDF压缩工具推荐
windows
神秘人X7075 小时前
Linux网络配置全攻略:IP、路由与双机通信
linux·网络·tcp/ip