Skip to content

Use ipaddress.ip_address instead of regex to detect IPv4 string in http.cookiejar #135500

Open
@LamentXU123

Description

@LamentXU123

Feature or enhancement

Proposal:

In stdlib http.cookiejar we've got a IPV4_RE constant:

IPV4_RE = re.compile(r"\.\d+$", re.ASCII)

it is widely used in deciding whether a string is a HDN or a IP address. such as:

def liberal_is_HDN(text):
    """Return True if text is a sort-of-like a host domain name.

    For accepting/blocking domains.

    """
    if IPV4_RE.search(text):
        return False
    return True

but the regex only checks if the string ends with a dot and some numbers. IMO

  • Firstly, we could add number ranges in the regex as numbers in IPv4 couldn't be bigger than 255
  • Secondly, it does not support IPv6, address like 2001:db8::1 would be detected as a HDN which is completely wrong.

The author also stated that in is_HDN():

    # XXX
    # This may well be wrong.  Which RFC is HDN defined in, if any (for
    #  the purposes of RFC 2965)?
    # For the current implementation, what about IPv6?  Remember to look
    #  at other uses of IPV4_RE also, if change this.

Since we've got ipaddress lib. I think we can use ipaddress to decide whether a string is a IP address or a HDN.

def is_ip(text):
    """Return True if text is a valid IP address."""
    # This function is a replacement of regex `IPV4_RE` in previous versions.
    try:
        ip_address(text)
        return True
    except ValueError:
        return False

Has this already been discussed elsewhere?

I have already discussed this feature proposal on Discourse

Links to previous discussion of this feature:

https://discuss.python.org/t/support-ipv6-in-http-cookiejar-when-deciding-whether-a-string-is-a-hdn-or-a-ip-addr/95439

Linked PRs

Metadata

Metadata

Assignees

No one assigned

    Labels

    stdlibPython modules in the Lib dirtype-featureA feature request or enhancement

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions