title: Regular Expression for hostname & ip
body: <p>I'm trying to find a regex to validate IP-Addresses and one for Hostnames in Javascript.</p>
  
  <p>I looked at many posts here and elsewhere but cannot quite find one that suits my needs.</p>
  
  <p>For the IP I found two that work fine (dont know if there are differences other than the format):</p>
  
  <p>1: (this is my preferred regex for IP-Addresses)</p>
  
  <pre><code>^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$
  </code></pre>
  
  <p>2:</p>
  
  <pre><code>^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$
  </code></pre>
  
  <p>For the Hostname I found this one:</p>
  
  <pre><code>/^(([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]*[a-zA-Z0-9])\.)*([A-Za-z0-9]|[A-Za-z0-9][A-Za-z0-9\-]*[A-Za-z0-9])$/
  </code></pre>
  
  <p>which also works fine.</p>
  
  <p>BUT^^ the problem is that the hostname regex will validate </p>
  
  <pre><code>192.168.178.1111
  </code></pre>
  
  <p>This is not a hostname, this is an invalid IP-Address.</p>
  
  <p>I would like to fit both hostname &amp; IP regex together in a single regex term but since the hostname regex will validate any non-valid IP-Address I cannot combine them.</p>
  
  <p>Does anyone have an idea on how to create a hostname regex that will not validate an invalid IP-Address?</p>
  
  <p>EDIT: I found this one as well:
  <a href="http://jsfiddle.net/opd1v7au/2/" rel="nofollow noreferrer">http://jsfiddle.net/opd1v7au/2/</a></p>
  
  <p>but this will validate for example:</p>
  
  <pre><code>::2:3:4:5
  </code></pre>
  
  <p>which my application cannot accept.</p>
  
  <hr>
  
  <p><strong>Solution:</strong> thx to <a href="https://stackoverflow.com/users/1678362/aaron">Aaron</a> I have this regex for now which seems to work (in testing at the moment)</p>
  
  <pre><code>^(([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]*[a-zA-Z0-9])\.)+([A-Za-z]|[A-Za-z][A-Za-z0-9\-]*[A-Za-z0-9])$
  </code></pre>
  
  <p>Combined version to validate IP-Addresses &amp; Hostnames <a href="http://regexr.com/3dt4r" rel="nofollow noreferrer">->RegExr.com</a>:</p>
  
  <pre><code>^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$|^(([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]*[a-zA-Z0-9])\.)+([A-Za-z]|[A-Za-z][A-Za-z0-9\-]*[A-Za-z0-9])$
  </code></pre>