In one project, I had to check if the passed string was a domain, so I dealt with it there.
import socket
domain = "qiita.com"
class DomainError(BaseException): pass
def check_domain(domain):
if domain.find(".") != -1:
try:
host = socket.gethostbyname(domain)
return True
except socket.gaierror:
raise DomainError("domain not found.")
else:
raise DomainError("this is not domain.")
First, check if the domain string contains dots, and then use the socket.gethostbyname
function of the ** socket ** module to convert the ** domain string to an IP address. ** If this works, it returns True because the given domain string is a normal domain. If the function gives an error, it's not a normal domain and throws an error.
Recommended Posts