Dipanjan
Dipanjan

Reputation: 301

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

Is it possible to find out a string is a FQDN or an IP address using boost lib in c++. I have tried the below code which works fine for IP address but throws exception in case of 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;
}

The fails in case of FQDN , as boost::asio::ip::address throws an exception in case of FQDN.

I have also tried searching for the same, in python something similar is availble but I need in c++.

Upvotes: 3

Views: 989

Answers (1)

selbie
selbie

Reputation: 104514

Easy solution is that you just catch the exception thrown by addr.from_string

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

Or if exceptions bother you, call the 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;
    }

Otherwise, just use inet_pton which is available everywhere.

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);
}

Upvotes: 4

Related Questions