diff --git a/src/platform/linux/misc.cpp b/src/platform/linux/misc.cpp index b4311265..c274783b 100644 --- a/src/platform/linux/misc.cpp +++ b/src/platform/linux/misc.cpp @@ -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; @@ -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