Language: Python
Label: safe
CWE: CWE-918 \u2014 Server-Side Request Forgery (SSRF)
The web server receives a URL or similar request from an upstream component and retrieves the contents of this URL, but it does not sufficiently ensure that the request is being sent to the expected destination.

Code:
def extract_ip_or_domain(url):
    ip_regex = re.compile("^(?:http\:\/\/|https\:\/\/)(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})")
    domain_regex = re.compile("^(?:http\:\/\/|https\:\/\/)([a-zA-Z0-9.-]+)")

    match = ip_regex.findall(url)
    if len(match):
        ip_address = match[0]
        try:
            ipaddress.ip_address(ip_address)  # Validate the IP address
            return ip_address
        except ValueError:
            pass

    match = domain_regex.findall(url)
    if len(match):
        return match[0]

    return None