1
0
mirror of https://github.com/home-assistant/core.git synced 2025-12-24 12:59:34 +00:00

Add is_host_valid util (#76589)

This commit is contained in:
Artem Draft
2022-09-11 19:12:04 +03:00
committed by GitHub
parent b0777e6280
commit 29be6d17b0
6 changed files with 47 additions and 56 deletions

View File

@@ -2,6 +2,7 @@
from __future__ import annotations
from ipaddress import IPv4Address, IPv6Address, ip_address, ip_network
import re
import yarl
@@ -86,6 +87,20 @@ def is_ipv6_address(address: str) -> bool:
return True
def is_host_valid(host: str) -> bool:
"""Check if a given string is an IP address or valid hostname."""
if is_ip_address(host):
return True
if len(host) > 255:
return False
if re.match(r"^[0-9\.]+$", host): # reject invalid IPv4
return False
if host.endswith("."): # dot at the end is correct
host = host[:-1]
allowed = re.compile(r"(?!-)[A-Z\d\-]{1,63}(?<!-)$", re.IGNORECASE)
return all(allowed.match(x) for x in host.split("."))
def normalize_url(address: str) -> str:
"""Normalize a given URL."""
url = yarl.URL(address.rstrip("/"))