Linux系统获取本地IP
源码
以下获取系统IP的代码片
,已在x86,docker,TDA4,xavier,mdc610平台测试通过.
#include <arpa/inet.h>
#include <ifaddrs.h>
#include <netdb.h>
#include <unistd.h>
#include <string>
#include <iostream>
static std::string host_name_;
static std::string host_ip_;
void GetHostInfo() {
char host_name[1024];
gethostname(host_name, sizeof(host_name));
host_name_ = host_name;
host_ip_ = "127.0.0.1";
// if we have exported a non-loopback CYBER_IP, we will use it firstly,
// otherwise, we try to find first non-loopback ipv4 addr.
const char* ip_env = getenv("CYBER_IP");
if (ip_env != nullptr) {
// maybe we need to verify ip_env
std::string ip_env_str(ip_env);
std::string starts = ip_env_str.substr(0, 3);
if (starts != "127") {
host_ip_ = ip_env_str;
std::cout << "host ip: " << host_ip_ << std::endl;
return;
}
}
ifaddrs* ifaddr = nullptr;
if (getifaddrs(&ifaddr) != 0) {
std::cout << "getifaddrs failed, we will use 127.0.0.1 as host ip." << std::endl;
return;
}
for (ifaddrs* ifa = ifaddr; ifa; ifa = ifa->ifa_next) {
if (ifa->ifa_addr == nullptr) {
continue;
}
int family = ifa->ifa_addr->sa_family;
if (family != AF_INET) {
continue;
}
char addr[NI_MAXHOST] = {0};
if (getnameinfo(ifa->ifa_addr, sizeof(sockaddr_in), addr, NI_MAXHOST, NULL,
0, NI_NUMERICHOST) != 0) {
continue;
}
std::string tmp_ip(addr);
std::string starts = tmp_ip.substr(0, 3);
if (starts != "127") {
host_ip_ = tmp_ip;
break;
}
}
freeifaddrs(ifaddr);
std::cout << "host ip: " << host_ip_ << std::endl;
}
int main()
{
GetHostInfo();
getchar();
}