Skip to content

Commit

Permalink
Try fix get_local_ip_for_gateway for Linux
Browse files Browse the repository at this point in the history
  • Loading branch information
ClassicOldSong committed Sep 13, 2024
1 parent 2617b17 commit 80ea11b
Showing 1 changed file with 44 additions and 40 deletions.
84 changes: 44 additions & 40 deletions src/platform/linux/misc.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -241,43 +241,43 @@ namespace platf {
return "00:00:00:00:00:00"s;
}

std::string
get_local_ip_for_gateway() {
int fd = socket(AF_NETLINK, SOCK_RAW, NETLINK_ROUTE);
if (fd < 0) {
BOOST_LOG(warning) << "Socket creation failed";
return "";
}

char buffer[8192];
struct nlmsghdr *nlMsg = (struct nlmsghdr *)buffer;
struct rtmsg *rtMsg = (struct rtmsg *)NLMSG_DATA(nlMsg);
struct rtattr *rtAttr;
int len = 0;

memset(nlMsg, 0, sizeof(struct nlmsghdr));
nlMsg->nlmsg_len = NLMSG_LENGTH(sizeof(struct rtmsg));
nlMsg->nlmsg_type = RTM_GETROUTE;
nlMsg->nlmsg_flags = NLM_F_DUMP | NLM_F_REQUEST;
nlMsg->nlmsg_seq = 1;
nlMsg->nlmsg_pid = getpid();

if (send(fd, nlMsg, nlMsg->nlmsg_len, 0) < 0) {
close(fd);
BOOST_LOG(warning) << "Send message failed";
return "";
}
std::string
get_local_ip_for_gateway() {
int fd = socket(AF_NETLINK, SOCK_RAW, NETLINK_ROUTE);
if (fd < 0) {
BOOST_LOG(warning) << "Socket creation failed: " << strerror(errno);
return "";
}

len = recv(fd, nlMsg, sizeof(buffer), 0);
if (len < 0) {
close(fd);
BOOST_LOG(warning) << "Receive message failed";
return "";
}
char buffer[8192];
struct nlmsghdr *nlMsg = (struct nlmsghdr *)buffer;
struct rtmsg *rtMsg = (struct rtmsg *)NLMSG_DATA(nlMsg);
struct rtattr *rtAttr;
int len = 0;

memset(nlMsg, 0, sizeof(struct nlmsghdr));
nlMsg->nlmsg_len = NLMSG_LENGTH(sizeof(struct rtmsg));
nlMsg->nlmsg_type = RTM_GETROUTE;
nlMsg->nlmsg_flags = NLM_F_DUMP | NLM_F_REQUEST;
nlMsg->nlmsg_seq = 1;
nlMsg->nlmsg_pid = getpid();

if (send(fd, nlMsg, nlMsg->nlmsg_len, 0) < 0) {
BOOST_LOG(warning) << "Send message failed: " << strerror(errno);
close(fd);
return "";
}

std::string local_ip;
std::string local_ip;
bool found = false;

while ((len = recv(fd, nlMsg, sizeof(buffer), 0)) > 0) {
for (; NLMSG_OK(nlMsg, len); nlMsg = NLMSG_NEXT(nlMsg, len)) {
if (nlMsg->nlmsg_type == NLMSG_DONE) {
found = true;
break;
}

rtMsg = (struct rtmsg *)NLMSG_DATA(nlMsg);
if (rtMsg->rtm_family != AF_INET || rtMsg->rtm_table != RT_TABLE_MAIN)
continue;
Expand All @@ -304,18 +304,22 @@ namespace platf {
}

if (gateway.s_addr != 0 && local.s_addr != 0) {
local_ip = inet_ntoa(local);
break;
local_ip = inet_ntoa(local);
found = true;
break;
}
}

close(fd);
if (found) break;
}

if (local_ip.empty()) {
BOOST_LOG(warning) << "No associated IP address found for the default gateway";
}
close(fd);

if (local_ip.empty()) {
BOOST_LOG(warning) << "No associated IP address found for the default gateway";
}

return local_ip;
return local_ip;
}

bp::child
Expand Down

0 comments on commit 80ea11b

Please sign in to comment.