From 73707653c589ebd45adc6a4bf530068465923ea0 Mon Sep 17 00:00:00 2001 From: cpan Date: Mon, 1 Jul 2024 15:38:17 +0800 Subject: [PATCH] =?UTF-8?q?[mars]=E5=A2=9E=E5=8A=A0=E6=9C=AC=E5=9C=B0ip?= =?UTF-8?q?=E5=9C=B0=E5=9D=80=E7=9A=84=E6=A3=80=E6=9F=A5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- mars/comm/network/netinfo_util.cc | 49 +++++++++++++++++++++++++++++++ mars/comm/network/netinfo_util.h | 2 +- 2 files changed, 50 insertions(+), 1 deletion(-) diff --git a/mars/comm/network/netinfo_util.cc b/mars/comm/network/netinfo_util.cc index 1175f73d7..960f9d374 100644 --- a/mars/comm/network/netinfo_util.cc +++ b/mars/comm/network/netinfo_util.cc @@ -29,6 +29,7 @@ #include "comm/socket/socket_address.h" #include "comm/socket/unix_socket.h" #include "comm/xlogger/xlogger.h" +#include "mars/comm/network/getaddrinfo_with_timeout.h" using namespace mars::comm; @@ -165,3 +166,51 @@ std::string GetDetailNetInfo(bool _need_wifi_ssid) { } return detail_net_info.Message(); } + +int get_local_ip(std::vector& ips) { + // 获取主机名 + char hostname[256]; + if (gethostname(hostname, sizeof(hostname)) == -1) { + xerror2(TSF "gethostname failed"); + return -1; + } + struct addrinfo hints, *single, *res; + memset(&hints, 0, sizeof(hints)); + hints.ai_family = AF_UNSPEC; // 允许IPv4和IPv6 + hints.ai_socktype = SOCK_STREAM; + hints.ai_flags = AI_PASSIVE; + + bool is_timeout = false; + if (getaddrinfo_with_timeout(hostname, NULL, &hints, &res, is_timeout, 2000) != 0) { + xerror2(TSF "getaddrinfo failed"); + return -1; + } + + for (single = res; single; single = single->ai_next) { + // In Indonesia, if there is no ipv6's ip, operators return 0.0.0.0. + if (PF_INET == single->ai_family) { + sockaddr_in* addr_in = (sockaddr_in*)single->ai_addr; + // struct in_addr convertAddr; + /*need no filter + if (INADDR_ANY == addr_in->sin_addr.s_addr || INADDR_NONE == addr_in->sin_addr.s_addr) { + xwarn2(TSF "hehe, addr_in->sin_addr.s_addr:%0", addr_in->sin_addr.s_addr); + continue; + }*/ + } + + socket_address sock_addr(single->ai_addr); + const char* ip = sock_addr.ip(); + + /*need no filter + if (!socket_address(ip, 0).valid_server_address(false, true)) { + xerror2(TSF "ip is invalid, ip:%0", ip); + continue; + } + */ + + ips.push_back(ip); + } + + freeaddrinfo(res); + return -1; +} diff --git a/mars/comm/network/netinfo_util.h b/mars/comm/network/netinfo_util.h index 723c60968..1f0a352ef 100644 --- a/mars/comm/network/netinfo_util.h +++ b/mars/comm/network/netinfo_util.h @@ -33,5 +33,5 @@ typedef enum { NetworkType GetNetworkType(); std::string GetDetailNetInfo(bool _need_wifi_ssid = true); - +int get_local_ip(std::vector& ips); #endif /* SRC_NETINFO_UTIL_H_ */