File size: 1,891 Bytes
4a4c0cf
3a1c55b
4a4c0cf
 
 
3a1c55b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4a4c0cf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e60e679
4a4c0cf
 
 
 
 
 
 
 
3e25ded
4a4c0cf
 
3e25ded
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
import re
import socket
import dns.resolver


def is_port_open(host: str, port: int, timeout: float = 1.0) -> bool:
    """
    Checks if a TCP port is open on a given host.

    Args:
        host: The hostname or IP address to check.
        port: The port number to check.
        timeout: The connection timeout in seconds.

    Returns:
        True if the port is open and a connection can be established,
        False otherwise.
    """
    try:
        with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
            s.settimeout(timeout)
            s.connect((host, port))
        print(f"TCP check successful: Port {port} is open on {host}.")
        return True
    except (socket.timeout, ConnectionRefusedError, OSError) as e:
        print(f"TCP check failed: Port {port} on {host} is not open. Error: {e}")
        return False


def validate_email(email_address: str) -> bool:
    """
    Validates an email address using regex for format and
    DNS for domain's MX record.

    Args:
        email_address (str): The email address to validate.

    Returns:
        bool: True if the email is syntactically valid and
              the domain has an MX record, False otherwise.
    """
    # Regex validation for basic format
    regex = r"[^@]+@[^@]+\.[^@]+"
    if not re.match(regex, email_address):
        return False

    # DNS MX record validation
    try:
        domain = email_address.rsplit("@", 1)[-1]
        dns.resolver.resolve(domain, "MX")
        return True
    except (dns.resolver.NoAnswer, dns.resolver.NXDOMAIN, IndexError):
        return False
    except Exception as e:
        print(f"An unexpected error occurred: {e}")
        return False


def strtobool(value: str) -> bool:
    if not value:
        return False
    value = value.lower()
    if value in ("y", "yes", "on", "1", "true", "t"):
        return True
    return False