isHostname function
Returns true if str is a valid hostname label sequence (RFC 1123).
Unlike isFQDN a top-level domain is not required, so a single label such
as localhost passes.
Implementation
bool isHostname(String str) {
if (str.isEmpty || str.length > 253) return false;
final withoutTrailingDot =
str.endsWith('.') ? str.substring(0, str.length - 1) : str;
if (withoutTrailingDot.isEmpty) return false;
final label = RegExp(r'^[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?$');
return withoutTrailingDot.split('.').every(label.hasMatch);
}