Python - validate a url as having a domain name or ip address

python, url

Solution

I think this does what you want:

import socket
def good_netloc(netloc):
    try:
        socket.gethostbyname(netloc)
        return True
    except:
        return False

print good_netloc("google.com")
print good_netloc("googlecom")
print good_netloc("10.1.1.1")
print good_netloc("999.999.999.999")

The output of this snippet is:

lap:~$ python tmp.py
True
False
True
False

Problem

I need to validate a url in Python and ensure that the host/netloc component is a domain name or ip v4/v6 address. Most StackOverflow Q&As on this general topic say to "just use `urlparse`". That is not applicable to this situation. I have already used `urlparse` to validate that I do indeed have a url. The problem is that I need to further validate the `.netloc` from urlparse to ensure that I am getting a Domain Name OR IP Address, and not just a hostname. Let me illustrate: ``` >>> from urlparse import urlparse ``` This works as expected / desired : ``` >>> ## domain name >>> print urlparse("http://example.com").netloc example.com >>> ## ipv4 >>> print urlparse("http://255.255.255.255").netloc 255.255.255.255 >>> ## acceptable hostname >>> print urlparse("http://localhost").netloc localhost ``` But I often run into typos that will let a malformed URL slip through. Someone might accidentally miss a '.' in a domain name: ``` >>> ## valid hostname, but unacceptable >>> print urlparse("http://examplecom").netloc examplecom ``` `examplecom` is indeed a valid hostname, and could exist on a network, but it is not a valid domain name. There also doesn't seem to be any rules enforced for IP Addresses : ``` >>> print urlparse("http://266.266.266.266").netloc 266.266.266.266 >>> print urlparse("http://999.999.999.999.999").netloc 999.999.999.999.999 ```

Original source

Related problems