找出 std::string 中存储的主机名是 C++ 中的 IP 地址还是 FQDN 地址

Finding out if an stored hostname in std::string is a ip address or a FQDN address in C++

是否可以在 C++ 中使用 boost lib 找出字符串是 FQDN 或 IP 地址。 我已经尝试了下面的代码,它适用于 IP 地址,但在 FQDN 的情况下会抛出异常。

// getHostname returns IP address or FQDN
std::string getHostname()
{
  // some work and find address and return
  return hostname;
}

bool ClassName::isAddressFqdn()
{
  const std::string hostname = getHostname();
  boost::asio::ip::address addr;
  addr.from_string(hostname.c_str());
  //addr.make_address(hostname.c_str()); // make_address does not work in my boost version

  if ((addr.is_v6()) || (addr.is_v4()))
  {
    std::cout << ":: IP address : " << hostname << std::endl;
    return false;
  }

  // If address is not an IPv4 or IPv6, then consider it is FQDN hostname
  std::cout << ":: FQDN hostname: " << hostname << std::endl;
  return true;
}

在 FQDN 的情况下失败,因为 boost::asio::ip::address 在 FQDN 的情况下抛出异常。

我也尝试过搜索相同的东西,在 python 中有类似的东西可用,但我需要在 c++ 中。

简单的解决方案是您只捕获 addr.from_string

抛出的异常
try
{
    addr.from_string(hostname.c_str());
}
catch(std::exception& ex)
{
    // not an IP address
    return true;
}

或者如果异常情况困扰您,请致电 no-throw version of from_string:

    boost::system::error_code ec;
    addr.from_string(hostname.c_str(), ec);
    if (ec)
    {
        // not an IP address
        return true;
    }

否则,只需使用随处可用的inet_pton

bool IsIpAddress(const char* address)
{
    sockaddr_in addr4 = {};
    sockaddr_in6 addr6 = {};

    int result4 = inet_pton(AF_INET, address, (void*)(&addr4));
    int result6 = inet_pton(AF_INET6, address, (void*)(&addr6));

    return ((result4 == 1) || (result6 == 1));
}

bool isAddressFqdn(const char* address)
{
    return !IsIpAddress(address);
}