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