Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[mars]增加本地ip地址的检查 #1287

Open
wants to merge 1 commit into
base: release/ios/2024-t1.1
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
49 changes: 49 additions & 0 deletions mars/comm/network/netinfo_util.cc
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand Down Expand Up @@ -165,3 +166,51 @@ std::string GetDetailNetInfo(bool _need_wifi_ssid) {
}
return detail_net_info.Message();
}

int get_local_ip(std::vector<std::string>& 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;
}
2 changes: 1 addition & 1 deletion mars/comm/network/netinfo_util.h
Original file line number Diff line number Diff line change
Expand Up @@ -33,5 +33,5 @@ typedef enum {

NetworkType GetNetworkType();
std::string GetDetailNetInfo(bool _need_wifi_ssid = true);

int get_local_ip(std::vector<std::string>& ips);
#endif /* SRC_NETINFO_UTIL_H_ */