是否有可能在 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/