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

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

是否有可能在 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);
}

关于c++11 - 找出 std::string 中存储的主机名是 C++ 中的 IP 地址还是 FQDN 地址,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62291688/

相关文章:

c++ - 模板化枚举类运算符

c++ - Boost Beast 异步服务器因断言失败而失败:(id_!= T::id) 在多个 aync 调用中

Python - 将包含 IP 地址和不同数据的文本文件的列表转换为 CSV

c++ - 线程安全,在C++中有序映射/哈希?

c++ - g++ 4.4 中 std::atomic<const memberfunctionpointer*>::store() 的 undefined reference

c++ - Boost Asio C++ HTTPS 请求未命中服务器。没有错误

c++ - Boost ASIO async_read 不从客户端读取数据

c++ - 确定服务器上已连接客户端的 IP 地址

c# - 警告 CS0618 : 'IPAddress.Address' is obsolete: 'This property has been deprecated

c++ - 如何为小数点分隔符和位数调整 std::stod(字符串加倍)