Public feed #887318

Something

public text v1 · immutable
Raw Edit
·published 2008-02-01 06:58 UTC
rendered paste body
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;

namespace Example
{
	public class MainClass
	{
		public static void Main ()
		{
			string fileName = "/etc/resolv.conf";
			foreach (IPAddress address in ParseResolvConf (fileName)) {
				Console.WriteLine ("> {0}", address.ToString ());
			}
		}

		/**
		 * ParseResolvConf:
		 * @fileName: a path to a file containing the dns configuration.
		 *
		 * This method will parse the resolver information from what is
		 * typically the resolv.conf on Unix platforms. This is one of
		 * the few things that is pretty well standard across all Unix
		 * implementations.
		 *
		 * We only care about the nameserver lines which are allowed
		 * one host per line with an optional port. However, the framework
		 * does not support DNS on ports other than the standard (53), so
		 * lines with non-standard ports will be ignored.
		 *
		 * Example:
		 *   192.168.0.1	  # Standard Port
		 *   192.168.0.1.55   # Use port 55
		 *
		 * The later will be ignored since we must return IPAddress
		 * structs only.
		 *
		 * Returns: An array of IPAddress structs containing the
		 * successfully parsed nameservers.
		 */
		static IPAddress[] ParseResolvConf (string fileName)
		{
			List<IPAddress> dnsServers = new List<IPAddress> ();

			using (StreamReader reader = new StreamReader (fileName)) {
				while (!reader.EndOfStream) {
					string line = reader.ReadLine ();
					
					if (line.StartsWith ("nameserver ")) {
						string[] parts = line.Split (' ');
						if (parts.Length < 2)
							continue;

						parts = parts[1].Split ('.');

						if (parts.Length == 4) {
							dnsServers.Add (IPAddress.Parse (String.Join (".", parts)));
						} else if (parts.Length == 5 && String.Equals (parts[4], "53")) {
							dnsServers.Add (IPAddress.Parse (String.Join (".", parts, 0, 4)));
						}
					}
				}
			}

			return dnsServers.ToArray ();
		}
	}
}