Commit dd821784 authored by aligungr's avatar aligungr

GetIp4 improvements for network interface IP addresses.

parent 375d5382
......@@ -14,7 +14,12 @@
#include <queue>
#include <stack>
#include <arpa/inet.h>
#include <dirent.h>
#include <net/if.h>
#include <netinet/in.h>
#include <sys/ioctl.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
......@@ -183,4 +188,34 @@ void AppendPath(std::string &source, const std::string &target)
source += target;
}
std::string GetIp4OfInterface(const std::string &ifName)
{
std::string res;
struct ifreq ifr = {};
int fd = socket(AF_INET, SOCK_DGRAM, 0);
if (fd <= 0)
return "";
ifr.ifr_addr.sa_family = AF_INET;
strncpy(ifr.ifr_name, ifName.c_str(), IFNAMSIZ - 1);
if (ioctl(fd, SIOCGIFADDR, &ifr))
{
close(fd);
return "";
}
close(fd);
auto address = ((struct sockaddr_in *)&ifr.ifr_addr)->sin_addr;
char str[INET_ADDRSTRLEN] = {0};
if (inet_ntop(AF_INET, &address, str, INET_ADDRSTRLEN) == nullptr)
return "";
return std::string{str};
}
} // namespace io
......@@ -40,4 +40,6 @@ std::string GetStem(const std::string &path);
void AppendPath(std::string &source, const std::string &target);
std::string GetIp4OfInterface(const std::string &ifName);
} // namespace io
......@@ -8,6 +8,7 @@
#include "yaml_utils.hpp"
#include "common.hpp"
#include "io.hpp"
#include <cctype>
#include <stdexcept>
......@@ -143,11 +144,19 @@ int64_t GetInt64(const YAML::Node &node, const std::string &name, std::optional<
std::string GetIp4(const YAML::Node &node, const std::string &name)
{
std::string ip = GetString(node, name);
int version = utils::GetIpVersion(ip);
if (version != 4)
FieldError(name, "must be a valid IPv4 address");
return ip;
std::string s = GetString(node, name);
int version = utils::GetIpVersion(s);
if (version == 6)
FieldError(name, "must be a valid IPv4 address or a valid network interface with a IPv4 address");
if (version == 4)
return s;
auto ipFromIf = io::GetIp4OfInterface(s);
if (ipFromIf.empty())
FieldError(name, "must be a valid IPv4 address or a valid network interface with a IPv4 address");
return ipFromIf;
}
void AssertHasBool(const YAML::Node &node, const std::string &name)
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment