使用条件编译结合gethostname和gethostbyname可跨平台获取本机IPv4地址,Windows需初始化Winsock,Linux直接调用网络API,该方法返回局域网IP;示例代码展示了基础实现,通过主机名解析IP并处理平台差异;对于多网卡或IPv6需求,应使用getifaddrs(Linux)或GetAdaptersAddresses(Windows)遍历接口信息,筛选有效非回环IPv4地址;为简化开发,推荐引入Boost.Asio库,通过模拟TCP连接获取本地地址,自动处理跨平台细节,提升稳定性和开发效率。

在C++中获取本机IP地址,跨平台实现需要考虑Windows和Linux/Unix系统的差异。直接使用平台相关的API虽然高效,但不利于代码移植。下面介绍一种通用思路,结合条件编译处理不同系统,稳定获取本地IPv4地址。
核心思路是通过gethostname获取主机名,再用gethostbyname(或现代替代函数)解析IP地址。注意:该方法获取的是局域网IP,非公网IP。
示例代码:
#include <iostream>
#include <string>
#ifdef _WIN32
#include <winsock2.h>
#pragma comment(lib, "ws2_32.lib")
#else
#include <sys/socket.h>
#include <netdb.h>
#include <unistd.h>
#include <arpa/inet.h>
#endif
<p>std::string getLocalIPAddress() {</p><p><span>立即学习</span>“<a href="https://pan.quark.cn/s/6e7abc4abb9f" style="text-decoration: underline !important; color: blue; font-weight: bolder;" rel="nofollow" target="_blank">C++免费学习笔记(深入)</a>”;</p>
<div class="aritcle_card">
<a class="aritcle_card_img" href="/ai/2073">
<img src="https://img.php.cn/upload/ai_manual/000/000/000/175680176528330.png" alt="稿定AI文案">
</a>
<div class="aritcle_card_info">
<a href="/ai/2073">稿定AI文案</a>
<p>小红书笔记、公众号、周报总结、视频脚本等智能文案生成平台</p>
<div class="">
<img src="/static/images/card_xiazai.png" alt="稿定AI文案">
<span>45</span>
</div>
</div>
<a href="/ai/2073" class="aritcle_card_btn">
<span>查看详情</span>
<img src="/static/images/cardxiayige-3.png" alt="稿定AI文案">
</a>
</div>
<h1>ifdef _WIN32</h1><pre class="brush:php;toolbar:false;"><pre class="brush:php;toolbar:false;">WSADATA wsaData;
WSAStartup(MAKEWORD(2, 2), &wsaData);char hostname[256];
if (gethostname(hostname, sizeof(hostname)) == 0) {
struct hostent* host = gethostbyname(hostname);
if (host != nullptr && host->h_addr_list[0] != nullptr) {
struct in_addr addr;
std::memcpy(&addr, host->h_addr_list[0], sizeof(struct in_addr));
std::string ip = inet_ntoa(addr);WSACleanup();
return ip;
}
}WSACleanup();
return "127.0.0.1";
}
上述方法可能只返回第一个IP,若机器有多个网卡或需支持IPv6,应使用getifaddrs(Linux)或GetAdaptersAddresses(Windows)遍历所有接口。
若项目允许引入外部依赖,推荐使用Boost.Asio。它封装了底层细节,提供统一接口:
#include <boost/asio.hpp>
std::string getLocalIP() {
boost::asio::io_service io;
boost::asio::ip::tcp::socket socket(io);
boost::asio::ip::tcp::endpoint endpoint(boost::asio::ip::address_v4::loopback(), 80);
socket.connect(endpoint);
return socket.local_endpoint().address().to_string();
}
此方法通过模拟连接获取绑定地址,适用于大多数场景,且自动处理跨平台问题。
基本上就这些。选择原生API适合轻量需求,用Boost则开发更快、稳定性更高。
以上就是c++++中如何获取本机IP地址_跨平台获取本地IP地址方案的详细内容,更多请关注php中文网其它相关文章!
c++怎么学习?c++怎么入门?c++在哪学?c++怎么学才快?不用担心,这里为大家提供了c++速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号