Try fix get_local_ip_for_gateway for Linux

This commit is contained in:
Yukino Song
2024-09-14 04:18:23 +08:00
parent 2617b17aab
commit 80ea11b815
+13 -9
View File
@@ -245,7 +245,7 @@ namespace platf {
get_local_ip_for_gateway() {
int fd = socket(AF_NETLINK, SOCK_RAW, NETLINK_ROUTE);
if (fd < 0) {
BOOST_LOG(warning) << "Socket creation failed";
BOOST_LOG(warning) << "Socket creation failed: " << strerror(errno);
return "";
}
@@ -263,21 +263,21 @@ namespace platf {
nlMsg->nlmsg_pid = getpid();
if (send(fd, nlMsg, nlMsg->nlmsg_len, 0) < 0) {
BOOST_LOG(warning) << "Send message failed: " << strerror(errno);
close(fd);
BOOST_LOG(warning) << "Send message failed";
return "";
}
len = recv(fd, nlMsg, sizeof(buffer), 0);
if (len < 0) {
close(fd);
BOOST_LOG(warning) << "Receive message failed";
return "";
}
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;
@@ -305,10 +305,14 @@ namespace platf {
if (gateway.s_addr != 0 && local.s_addr != 0) {
local_ip = inet_ntoa(local);
found = true;
break;
}
}
if (found) break;
}
close(fd);
if (local_ip.empty()) {