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

}

相关推荐
Predestination王瀞潞1 小时前
5.4.2 通信->WWW万维网内容访问标准(W3C):WWW(World Wide Web) 核心技术规范
网络·网络协议·https·www
新手88601 小时前
Oracle VirtualBox虚拟机安装 和 安装 window11版本虚拟机 及 启用EFI和硬盘无法使用 问题
服务器·windows·计算机网络·安全·虚拟机
门豪杰1 小时前
Windows下配置针对WSL的cc-switch
windows·claude·claude code·cc-switch·cc switch
虾..1 小时前
TCP协议
网络·网络协议·tcp/ip
姓王名礼2 小时前
一份 Windows/macOS/Linux 完整安装 + 运行 + 对接 WebUI 的步骤
linux·windows·macos
上去我就QWER2 小时前
详解HTTP协议中的multipart/form-data
网络·网络协议·http
开开心心就好2 小时前
绿色版PDF多功能工具,支持编辑转换
人工智能·windows·pdf·ocr·excel·语音识别·harmonyos
@encryption3 小时前
TCP,IP
服务器·网络·tcp/ip
武藤一雄3 小时前
C#常见面试题100问 (第一弹)
windows·microsoft·面试·c#·.net·.netcore
Predestination王瀞潞4 小时前
5.3.2 通信->HTTP3超文本传输协议标准(IETF RFC 9114):Headers 请求头 响应头
网络·网络协议·tcp/ip