title: Parsing host:port expressions
body: <p>What's the best and simplest way to parse an environment variable of the following possible forms: <code>host[:port]</code></p>
  
  <ul>
  <li><code>redis</code></li>
  <li><code>redis:6379</code></li>
  <li><code>10.0.0.72</code></li>
  <li><code>10.0.0.72:6379</code></li>
  <li><code>my.domain.name</code></li>
  <li><code>my.domain.name:6379</code></li>
  </ul>
  
  <p>The inputs are never prepended with a protocol.</p>
  
  <p>The end goal is to parse out the host and port in order to create an object of type <code>System.Net.IPEndPoint</code>, possibly after using <code>Dns.GetHostAddresses(host)[0]</code> depending on whether there is an ip or a hostname supplied in the environment variable.</p>
  
  <p>The purpose is helping dotnet core apps inside various docker containers discover each other according to values specified in their environment variables.</p>
  
  <p>I'm hoping to make use of parsing utilities already available in the dotnet core libraries rather than roll my own parser.</p>
  
  <p><code>new Uri("redis:6379")</code> produces invalid results.</p>
  
  <p><code>new Uri("https://redis:6379")</code> produces a Uri object with correct host and port properties, but it seems ridiculous to me that it should be necessary to malform all the inputs by prepending "https://" just to get the Uri object to parse it correctly.</p>
  
  <p><code>new Uri("https://redis")</code> incorrectly sets the <code>Port</code> property as 443 and doesn't indicate that it wasn't supplied in the user input.</p>
  
  <p>If it's possible to skip parsing steps and resolve straight to IPEndPoint with no in-between steps, that would be my preferred answer.</p>
  
  <p>This is what I'm using at the moment, with error handling removed. Have you got something better? </p>
  
  <pre><code>IPEndPoint ParseGateway(string input) {
      var parts = input.Split(':');
      var host = parts[0];
      var port = parts.Length &gt; 1 ? int.Parse(parts[1]) : DEFAULT_GATEWAY_PORT;
      var ip = Dns.GetHostAddresses(host)[0];
      return new IPEndPoint(ip, port);
  }
  </code></pre>