【问题标题】:Finding out if an stored hostname in std::string is a ip address or a FQDN address in C++找出 std::string 中存储的主机名是 C++ 中的 IP 地址还是 FQDN 地址
【发布时间】:2020-06-09 20:55:37
【问题描述】:

是否可以在 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++ 中。

【问题讨论】:

    标签: c++11 boost-asio ip-address fqdn


    【解决方案1】:

    简单的解决方案是你只捕获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);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-04-14
      • 1970-01-01
      • 2022-01-02
      • 1970-01-01
      • 1970-01-01
      • 2018-10-22
      • 2014-12-19
      相关资源
      最近更新 更多