Click here to Skip to main content
15,891,951 members
Articles / DevOps / Testing

Multithreaded DNS Tester

Rate me:
Please Sign up or sign in to vote.
4.94/5 (6 votes)
23 Jan 2013CPOL5 min read 21.7K   1.1K   26  
This is basicaly Charles Putney's dns tester but also is multithreaded and can be used with a static list
using System;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.Net;
using System.Net.Sockets;
using System.Security.Cryptography;
using System.Diagnostics;
using System.Threading;


namespace dnstester
{
	// Charles Putney
	// 18 Quinns Road
	// Co. Dublin
	// Ireland
	//
	// This file and the code contained within is freeware and may be
	// distributed and edited without restriction.
		// 
	// 
    
	public class DNSTester : System.Windows.Forms.Form
	{

        private string[] CleanNames;
        private int CleanNamesCount;
		private System.Windows.Forms.TextBox DNSBox1;
		private System.Windows.Forms.TextBox DNSBox2;
		private System.Windows.Forms.Label label1;
		private System.Windows.Forms.Label label2;
		private System.Windows.Forms.Button Testbutton;
		private System.Windows.Forms.ListView ResultView;
		private System.Windows.Forms.ColumnHeader DNS1Timing;
		private System.Windows.Forms.ColumnHeader DNS2Timing;
		private System.Windows.Forms.ColumnHeader WebName;
        private System.Windows.Forms.ListBox StatusBox;
		private System.Windows.Forms.Label label5;
		private System.Windows.Forms.ColumnHeader DNS1IP;
		private System.Windows.Forms.ColumnHeader DNS2IP;
		private System.Windows.Forms.TextBox HTTPProxyBox;
		private System.Windows.Forms.Label label6;
        private CheckBox chckBox_static;
        private object _dummy = new object();
        private CheckBox chckBox_strs;
        private TextBox textBox_strs;
        private Button btn_stop;
        private bool canrun;
        private int globalcounter;
        private StatusStrip statusStrip1;
        private ToolStripStatusLabel label_idle;
		
		/// <summary>
		/// Required designer variable.
		/// </summary>
		private System.ComponentModel.Container components = null;

		public DNSTester()
		{
			//
			// Required for Windows Form Designer support
			//
			InitializeComponent();
				
	

			//
			// TODO: Add any constructor code after InitializeComponent call
			//
		}

		/// <summary>
		/// Clean up any resources being used.
		/// </summary>
		protected override void Dispose( bool disposing )
		{
			if( disposing )
			{
				if (components != null) 
				{
					components.Dispose();
				}
			}
			base.Dispose( disposing );
		}

		#region Windows Form Designer generated code
		/// <summary>
		/// Required method for Designer support - do not modify
		/// the contents of this method with the code editor.
		/// </summary>
		private void InitializeComponent()
		{
            this.DNSBox1 = new System.Windows.Forms.TextBox();
            this.DNSBox2 = new System.Windows.Forms.TextBox();
            this.Testbutton = new System.Windows.Forms.Button();
            this.ResultView = new System.Windows.Forms.ListView();
            this.WebName = new System.Windows.Forms.ColumnHeader();
            this.DNS1IP = new System.Windows.Forms.ColumnHeader();
            this.DNS1Timing = new System.Windows.Forms.ColumnHeader();
            this.DNS2IP = new System.Windows.Forms.ColumnHeader();
            this.DNS2Timing = new System.Windows.Forms.ColumnHeader();
            this.StatusBox = new System.Windows.Forms.ListBox();
            this.HTTPProxyBox = new System.Windows.Forms.TextBox();
            this.label1 = new System.Windows.Forms.Label();
            this.label2 = new System.Windows.Forms.Label();
            this.label5 = new System.Windows.Forms.Label();
            this.label6 = new System.Windows.Forms.Label();
            this.chckBox_static = new System.Windows.Forms.CheckBox();
            this.chckBox_strs = new System.Windows.Forms.CheckBox();
            this.textBox_strs = new System.Windows.Forms.TextBox();
            this.btn_stop = new System.Windows.Forms.Button();
            this.statusStrip1 = new System.Windows.Forms.StatusStrip();
            this.label_idle = new System.Windows.Forms.ToolStripStatusLabel();
            this.statusStrip1.SuspendLayout();
            this.SuspendLayout();
            // 
            // DNSBox1
            // 
            this.DNSBox1.Location = new System.Drawing.Point(96, 40);
            this.DNSBox1.Name = "DNSBox1";
            this.DNSBox1.Size = new System.Drawing.Size(100, 20);
            this.DNSBox1.TabIndex = 12;
            this.DNSBox1.Text = "4.2.2.1";
            this.DNSBox1.TextChanged += new System.EventHandler(this.DNSBox1_TextChanged);
            // 
            // DNSBox2
            // 
            this.DNSBox2.Location = new System.Drawing.Point(292, 40);
            this.DNSBox2.Name = "DNSBox2";
            this.DNSBox2.Size = new System.Drawing.Size(100, 20);
            this.DNSBox2.TabIndex = 1;
            this.DNSBox2.Text = "152.158.16.48";
            this.DNSBox2.TextChanged += new System.EventHandler(this.DNSBox2_TextChanged);
            // 
            // Testbutton
            // 
            this.Testbutton.BackColor = System.Drawing.SystemColors.ButtonFace;
            this.Testbutton.FlatAppearance.BorderColor = System.Drawing.SystemColors.ButtonFace;
            this.Testbutton.FlatAppearance.MouseDownBackColor = System.Drawing.SystemColors.ButtonHighlight;
            this.Testbutton.FlatAppearance.MouseOverBackColor = System.Drawing.SystemColors.ButtonHighlight;
            this.Testbutton.FlatStyle = System.Windows.Forms.FlatStyle.System;
            this.Testbutton.Location = new System.Drawing.Point(632, 37);
            this.Testbutton.Name = "Testbutton";
            this.Testbutton.Size = new System.Drawing.Size(75, 23);
            this.Testbutton.TabIndex = 4;
            this.Testbutton.Text = "Test";
            this.Testbutton.UseVisualStyleBackColor = false;
            this.Testbutton.Click += new System.EventHandler(this.Testbutton_Click);
            // 
            // ResultView
            // 
            this.ResultView.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] {
            this.WebName,
            this.DNS1IP,
            this.DNS1Timing,
            this.DNS2IP,
            this.DNS2Timing});
            this.ResultView.FullRowSelect = true;
            this.ResultView.GridLines = true;
            this.ResultView.Location = new System.Drawing.Point(56, 80);
            this.ResultView.MultiSelect = false;
            this.ResultView.Name = "ResultView";
            this.ResultView.Size = new System.Drawing.Size(700, 344);
            this.ResultView.TabIndex = 11;
            this.ResultView.UseCompatibleStateImageBehavior = false;
            this.ResultView.View = System.Windows.Forms.View.Details;
            // 
            // WebName
            // 
            this.WebName.Text = "                  URL";
            this.WebName.Width = 160;
            // 
            // DNS1IP
            // 
            this.DNS1IP.Text = "IP Address from DNS 1";
            this.DNS1IP.TextAlign = System.Windows.Forms.HorizontalAlignment.Center;
            this.DNS1IP.Width = 140;
            // 
            // DNS1Timing
            // 
            this.DNS1Timing.Text = "DNS 1 Timing";
            this.DNS1Timing.TextAlign = System.Windows.Forms.HorizontalAlignment.Center;
            this.DNS1Timing.Width = 120;
            // 
            // DNS2IP
            // 
            this.DNS2IP.Text = "IP Address from DNS 2";
            this.DNS2IP.TextAlign = System.Windows.Forms.HorizontalAlignment.Center;
            this.DNS2IP.Width = 140;
            // 
            // DNS2Timing
            // 
            this.DNS2Timing.Text = "DNS 2 Timing";
            this.DNS2Timing.TextAlign = System.Windows.Forms.HorizontalAlignment.Center;
            this.DNS2Timing.Width = 120;
            // 
            // StatusBox
            // 
            this.StatusBox.HorizontalScrollbar = true;
            this.StatusBox.Location = new System.Drawing.Point(80, 456);
            this.StatusBox.Name = "StatusBox";
            this.StatusBox.Size = new System.Drawing.Size(616, 95);
            this.StatusBox.TabIndex = 13;
            // 
            // HTTPProxyBox
            // 
            this.HTTPProxyBox.Location = new System.Drawing.Point(488, 40);
            this.HTTPProxyBox.Name = "HTTPProxyBox";
            this.HTTPProxyBox.Size = new System.Drawing.Size(100, 20);
            this.HTTPProxyBox.TabIndex = 15;
            this.HTTPProxyBox.TextChanged += new System.EventHandler(this.HTTPProxyBox_TextChanged);
            // 
            // label1
            // 
            this.label1.Location = new System.Drawing.Point(96, 16);
            this.label1.Name = "label1";
            this.label1.Size = new System.Drawing.Size(100, 23);
            this.label1.TabIndex = 2;
            this.label1.Text = "DNS 1";
            this.label1.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
            // 
            // label2
            // 
            this.label2.Location = new System.Drawing.Point(288, 16);
            this.label2.Name = "label2";
            this.label2.Size = new System.Drawing.Size(100, 23);
            this.label2.TabIndex = 3;
            this.label2.Text = "DNS 2";
            this.label2.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
            // 
            // label5
            // 
            this.label5.Location = new System.Drawing.Point(16, 488);
            this.label5.Name = "label5";
            this.label5.Size = new System.Drawing.Size(56, 24);
            this.label5.TabIndex = 14;
            this.label5.Text = "Status";
            // 
            // label6
            // 
            this.label6.Location = new System.Drawing.Point(488, 16);
            this.label6.Name = "label6";
            this.label6.Size = new System.Drawing.Size(100, 23);
            this.label6.TabIndex = 16;
            this.label6.Text = "HTTP Proxy";
            this.label6.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
            // 
            // chckBox_static
            // 
            this.chckBox_static.AutoSize = true;
            this.chckBox_static.Location = new System.Drawing.Point(56, 431);
            this.chckBox_static.Name = "chckBox_static";
            this.chckBox_static.Size = new System.Drawing.Size(88, 17);
            this.chckBox_static.TabIndex = 17;
            this.chckBox_static.Text = "Use static list";
            this.chckBox_static.UseVisualStyleBackColor = true;
            // 
            // chckBox_strs
            // 
            this.chckBox_strs.AutoSize = true;
            this.chckBox_strs.Location = new System.Drawing.Point(151, 431);
            this.chckBox_strs.Name = "chckBox_strs";
            this.chckBox_strs.Size = new System.Drawing.Size(79, 17);
            this.chckBox_strs.TabIndex = 18;
            this.chckBox_strs.Text = "Stress Test";
            this.chckBox_strs.UseVisualStyleBackColor = true;
            this.chckBox_strs.CheckedChanged += new System.EventHandler(this.chckBox_strs_CheckedChanged);
            // 
            // textBox_strs
            // 
            this.textBox_strs.Enabled = false;
            this.textBox_strs.Location = new System.Drawing.Point(237, 431);
            this.textBox_strs.Name = "textBox_strs";
            this.textBox_strs.Size = new System.Drawing.Size(100, 20);
            this.textBox_strs.TabIndex = 19;
            // 
            // btn_stop
            // 
            this.btn_stop.Enabled = false;
            this.btn_stop.FlatAppearance.BorderColor = System.Drawing.SystemColors.ButtonFace;
            this.btn_stop.FlatAppearance.MouseDownBackColor = System.Drawing.SystemColors.ButtonHighlight;
            this.btn_stop.FlatAppearance.MouseOverBackColor = System.Drawing.SystemColors.ButtonHighlight;
            this.btn_stop.FlatStyle = System.Windows.Forms.FlatStyle.System;
            this.btn_stop.Location = new System.Drawing.Point(632, 37);
            this.btn_stop.Name = "btn_stop";
            this.btn_stop.Size = new System.Drawing.Size(75, 23);
            this.btn_stop.TabIndex = 20;
            this.btn_stop.Text = "Stop";
            this.btn_stop.UseVisualStyleBackColor = true;
            this.btn_stop.Visible = false;
            this.btn_stop.Click += new System.EventHandler(this.btn_stop_Click);
            // 
            // statusStrip1
            // 
            this.statusStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
            this.label_idle});
            this.statusStrip1.Location = new System.Drawing.Point(0, 551);
            this.statusStrip1.Name = "statusStrip1";
            this.statusStrip1.Size = new System.Drawing.Size(792, 22);
            this.statusStrip1.TabIndex = 22;
            this.statusStrip1.Text = "statusStrip1";
            // 
            // label_idle
            // 
            this.label_idle.Name = "label_idle";
            this.label_idle.Size = new System.Drawing.Size(26, 17);
            this.label_idle.Text = "Idle";
            this.label_idle.Click += new System.EventHandler(this.toolStripStatusLabel1_Click);
            // 
            // DNSTester
            // 
            this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
            this.BackColor = System.Drawing.SystemColors.Window;
            this.BackgroundImageLayout = System.Windows.Forms.ImageLayout.None;
            this.ClientSize = new System.Drawing.Size(792, 573);
            this.Controls.Add(this.statusStrip1);
            this.Controls.Add(this.btn_stop);
            this.Controls.Add(this.textBox_strs);
            this.Controls.Add(this.chckBox_strs);
            this.Controls.Add(this.chckBox_static);
            this.Controls.Add(this.HTTPProxyBox);
            this.Controls.Add(this.DNSBox1);
            this.Controls.Add(this.DNSBox2);
            this.Controls.Add(this.StatusBox);
            this.Controls.Add(this.ResultView);
            this.Controls.Add(this.Testbutton);
            this.Controls.Add(this.label1);
            this.Controls.Add(this.label2);
            this.Controls.Add(this.label5);
            this.Controls.Add(this.label6);
            this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle;
            this.MaximizeBox = false;
            this.Name = "DNSTester";
            this.ShowIcon = false;
            this.Text = "DNS Tester";
            this.Load += new System.EventHandler(this.DNSTester_Load);
            this.statusStrip1.ResumeLayout(false);
            this.statusStrip1.PerformLayout();
            this.ResumeLayout(false);
            this.PerformLayout();

		}
		#endregion

		/// <summary>
		/// The main entry point for the application.
		/// </summary>
		/// 
		private string DNS1,DNS2;
		private ListViewItem listURL = new ListViewItem();
		private ListViewItem.ListViewSubItem listDNS1IP = new ListViewItem.ListViewSubItem();		
		private ListViewItem.ListViewSubItem listDNS1time = new ListViewItem.ListViewSubItem();	
		private ListViewItem.ListViewSubItem listDNS2IP = new ListViewItem.ListViewSubItem();		
		private ListViewItem.ListViewSubItem listDNS2time = new ListViewItem.ListViewSubItem();

				
		

		[STAThread]
		
		static void Main() 
		{
			Application.Run(new DNSTester());
		}

		
		private void Testbutton_Click(object sender, System.EventArgs e)
		{
            label_idle.Text = "Working... , Please wait until the status becomes idle again.";
            canrun = true;
            Testbutton.Enabled = false;
            Testbutton.Visible = false;
            btn_stop.Enabled = true;
            btn_stop.Visible = true;
            if (textBox_strs.Text == "" && chckBox_strs.Checked)
            {
                MessageBox.Show("Please fill in how many times you want the stress test to check the DNS", "Ooops!", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            StatusBox.Items.Add("--------------------------------------------------------------------------------------------------------TEST-----------------------------------------------------------------------------------------");
            StatusBox.TopIndex = StatusBox.Items.Count - 1;
            if (StatusBox.Items.Count > 5000)
            {
                StatusBox.Items.RemoveAt(0);
            }
            StatusBox.Update();
            test();

		}
        private delegate void testdelegate();
        private void test()
        {

            try
            {
                CleanNames = new string[500];
                CleanNamesCount = 0;

                DNS1 = DNSBox1.Text;
                DNS2 = DNSBox2.Text;

                if (DNS1 == "")
                    throw new Exception("DNS 1 can not be empty");
                if (DNS2 == "")
                    throw new Exception("DNS 2 can not be empty");
                ResultView.Items.Clear();

                ResultView.Update();
                Application.DoEvents();
                _GetWebAddresses gwa = new _GetWebAddresses(GetWebAddresses);
                ThreadPool.QueueUserWorkItem(new WaitCallback(gwa));
                 
                Application.DoEvents();
            }
            catch (Exception err)
            {
                MessageBox.Show(err.Message, err.Source + " error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        private delegate void _GetWebAddresses(object obj);
		private  void GetWebAddresses(object obj)
        {
            _StatusBoxPrint print = new _StatusBoxPrint(StatusBoxPrint);
            int i, j;
            byte[] random = new Byte[256];
            string Letters = "";
            if (!chckBox_static.Checked)
            {
                // Make a 3 letter random string

                //RNGCryptoServiceProvider is an implementation of a random number generator.
                RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
                rng.GetBytes(random); // The array is now filled with cryptographically strong random bytes.
                for (i = 1; i < 256; i++)
                {
                    // Just take the first three letters
                    if (random[i] > 0x40 && random[i] < 0x5b) Letters = Letters + Convert.ToChar(random[i]);
                    if (Letters.Length == 3) break;
                }

                // Use Google to get random addresses for DNS testing

                // Initialize the WebRequest.
                StatusBox.Invoke(print, "Web Proxy set to: " + HTTPProxyBox.Text);
                StatusBox.Invoke(print, "Getting Google request");

                Application.DoEvents();
                try
                {

                    StreamWriter output = new StreamWriter("serverlist");
                    WebRequest GoogleRequest = WebRequest.Create("http://www.google.com/search?num=100&q=" + Letters); //Letters);
                    WebResponse GoogleResponse = GoogleRequest.GetResponse();
                    Application.DoEvents();
                    // Get the response stream.
                    Stream GoogleStream = GoogleResponse.GetResponseStream();
                    StatusBox.Invoke(print, "Google response received");

                    Application.DoEvents();
                    // Use a StreamReader to read the entire response.

                    StreamReader GoogleReader = new StreamReader(GoogleStream, Encoding.ASCII);
                    string GoogleString = GoogleReader.ReadToEnd();
                    // Close the response stream and response to free resources.
                    GoogleStream.Close();
                    GoogleResponse.Close();
                    Application.DoEvents();

                    // find all .xxx.com addresses
                    MatchCollection HostNames;
                    string[] Names = new string[1000];
                    // Create a new Regex object and define the regular expression.
                    Regex Dotcom = new Regex("[.]([A-Za-z]*)[.]com");
                    // Use the Matches method to find all matches in the input string.
                    HostNames = Dotcom.Matches(GoogleString);

                    Application.DoEvents();
                    // Loop through the match collection to retrieve all 
                    // matches and delete the leading "."
                    for (i = 0; i < HostNames.Count; i++)
                    {
                        Names[i] = HostNames[i].Value.Remove(0, 1);

                        Application.DoEvents();
                    }
                    // eliminate google.com and repeated entries
                    for (i = 0; i < HostNames.Count - 1; i++)
                    {
                        if (Names[i] == "google.com") Names[i] = "";
                        for (j = i + 1; j < HostNames.Count; j++)
                        {
                            if (Names[i] == Names[j]) Names[j] = "";

                            Application.DoEvents();
                        }
                    }
                    // count list and compact
                    j = 0;
                    for (i = 0; i < HostNames.Count; i++)
                    {

                        if (Names[i] != "")
                        {
                            CleanNames[j] = Names[i];
                            output.WriteLine(CleanNames[j]);
                            j++;
                        }

                        Application.DoEvents();
                    }
                    CleanNamesCount = j;
                    StatusBox.Invoke(print, CleanNamesCount + " Random URL's found");
                    output.Close();

                }
                catch
                {
                    StatusBox.Invoke(print, "Host Google.com not found - are you connected ?");
                }


            }
            else
            {
                try
                {
                    StatusBox.Invoke(print, "Using preloaded static list");
                    StreamReader input = new StreamReader("serverlist");
                    int k = 0;
                    string tmp;
                    while (!input.EndOfStream)
                    {
                        tmp=input.ReadLine();
                        if (tmp != "")
                        {
                            CleanNames[k] = tmp;
                            k++;
                        }
                    }

                    CleanNamesCount = k;
                    input.Close();
                }
                catch (Exception e)
                {
                    MessageBox.Show(e.Message, e.Source + " error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            try
            {
                _UpdateResultView urv = new _UpdateResultView(UpdateResultView);
                ResultView.Invoke(urv);
                CheckDNS(CleanNames, CleanNamesCount, DNS1, DNS2);
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message, e.Source + " error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
		}
        private delegate void _UpdateResultView();
        private void UpdateResultView()
        {

            int i;
            for (i = 0; i < CleanNamesCount; i++)
            {
                ListViewItem listURL = new ListViewItem(CleanNames[i]);
                listURL.SubItems.Add(" ");
                listURL.SubItems.Add(" ");
                listURL.SubItems.Add(" ");
                listURL.SubItems.Add(" ");
                ResultView.Items.Add(listURL);
            }
            ResultView.EnsureVisible(1);

            ResultView.Update();
        }
		private void CheckDNS(string[] URLNames, int URLNamescount, string DNSAddress1, string DNSAddress2)
		{
			int i;

            //const int DNSReceiveTimeout=5000;
            //ManualResetEvent[] doneEvents = new ManualResetEvent[URLNamescount];
            i = 0;
           // int TransactionDNS=0;
			// Start the clock
			// i=0; // for testing - do one
            mine me;
            globalcounter = 0;
			for (i=0;i<URLNamescount;i++)
			{

                if (!canrun)
                    return;
                _dnscheck ddnscheck = new _dnscheck(dnscheck);
                me = new mine(URLNames, URLNamescount, DNSAddress1, DNSAddress2, i);
               
                    ThreadPool.QueueUserWorkItem(new WaitCallback(ddnscheck), me);

                    globalcounter++;
			}
            //WaitHandle.WaitAll(me._doneEvent);
		

		}
        private delegate void _dnscheck(object me);
        private void dnscheck(object me)
        {

            int counter = 0;

            try
            {

                
                if (chckBox_strs.Checked)
                {

                    int tmpint = Convert.ToInt32(textBox_strs.Text.Trim());

                    for (int j = 0; j < tmpint && canrun; j++)
                    {
                        mine mo = (mine)me;
                        int i = mo.index;
                        string QueryString;
                        const string TransactionID1 = "Q1"; // Use transaction ID of Q1 and Q2 to identify our packet and DNS
                        const string TransactionID2 = "Q2";
                        const string TypeString = "\u0001" + "\u0000" + "\u0000" + "\u0001" + "\u0000" + "\u0000" + "\u0000" + "\u0000" + "\u0000" + "\u0000";
                        const string TrailerString = "\u0000" + "\u0000" + "\u0001" + "\u0000" + "\u0001";
                        int URLNameStartLength, DomainNameLength, index, TransactionDNS=0;
                        long StopTime;
                        string DeltaTime="";
                        string ReceiveString, IPResponse="";
                        string URLNameStart="", DomainName="";
                        const int IPPort = 53;
                        byte[] Receivebytes;
                        Socket DNSsocket;
                        byte[] Sendbytes;
                        Receivebytes = new byte[512];
                            counter = 0;
                            const int DNSReceiveTimeout = 5000;
                        third:

                            try
                            {
                            Receivebytes = new byte[512];

                            long StartTime;
                            if (counter == 1)
                            {
                                URLNameStart = mo.URLNames[i].Substring(0, mo.URLNames[i].IndexOf("."));
                                DomainName = mo.URLNames[i].Substring(mo.URLNames[i].IndexOf(".") + 1, mo.URLNames[i].Length - mo.URLNames[i].IndexOf(".") - 1);
                                IPEndPoint dnsEP2 = new IPEndPoint(IPAddress.Parse(mo.DNSAddress2), IPPort);
                                Sendbytes = new byte[256];
                                StartTime = DateTime.Now.Ticks;
                                DNSsocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
                                DNSsocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, DNSReceiveTimeout);
                                QueryString = TransactionID2 + TypeString + (char)URLNameStart.Length + URLNameStart + (char)DomainName.Length + DomainName + TrailerString;
                                Sendbytes = Encoding.ASCII.GetBytes(QueryString);
                                DNSsocket.SendTo(Sendbytes, Sendbytes.Length, SocketFlags.None, dnsEP2);
                            }




                            // Build the query 
                            else
                            {
                                StartTime = DateTime.Now.Ticks;
                                DNSsocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
                                DNSsocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, DNSReceiveTimeout);


                                Sendbytes = new byte[256];

                                URLNameStart = mo.URLNames[i].Substring(0, mo.URLNames[i].IndexOf("."));
                                DomainName = mo.URLNames[i].Substring(mo.URLNames[i].IndexOf(".") + 1, mo.URLNames[i].Length - mo.URLNames[i].IndexOf(".") - 1);
                                IPEndPoint dnsEP1 = new IPEndPoint(IPAddress.Parse(mo.DNSAddress1), IPPort);
                                QueryString = TransactionID1 + TypeString + (char)URLNameStart.Length + URLNameStart + (char)DomainName.Length + DomainName + TrailerString;
                                Sendbytes = Encoding.ASCII.GetBytes(QueryString);
                                DNSsocket.SendTo(Sendbytes, Sendbytes.Length, SocketFlags.None, dnsEP1);
                            }

                            // send the same message to both DNS servers except for the transaction ID


                            // wait for a response up to timeout
                        second:
                            DNSsocket.Receive(Receivebytes);


                            // make sure the message returned is ours
                            if (Receivebytes[0] == Sendbytes[0] && (Receivebytes[1] == 0x31) || (Receivebytes[1] == 0x32))
                            {
                                if (Receivebytes[2] == 0x81 && Receivebytes[3] == 0x80)
                                {
                                    // Get the time now
                                    StopTime = DateTime.Now.Ticks;
                                    DeltaTime = Convert.ToString((double)(StopTime - StartTime) / 10000000);

                                    // Decode the answers
                                    // Find the URL that was returned
                                    TransactionDNS = Receivebytes[1];
                                    ReceiveString = Encoding.ASCII.GetString(Receivebytes);
                                    index = 12;
                                    URLNameStartLength = Receivebytes[index];
                                    index++;
                                    URLNameStart = ReceiveString.Substring(index, URLNameStartLength);
                                    index = index + URLNameStartLength;
                                    DomainNameLength = Receivebytes[index];
                                    index++;
                                    DomainName = ReceiveString.Substring(index, DomainNameLength);
                                    index = index + DomainNameLength;
                                    index = index + 8;

                                    // Get the record type
                                    int ResponseType = Receivebytes[index];
                                    index = index + 9;

                                    // Get the IP address if applicable
                                    IPResponse = "";
                                    switch (ResponseType)
                                    {
                                        case 1: IPResponse = Convert.ToString(Receivebytes[index]) + "."
                                                    + Convert.ToString(Receivebytes[index + 1]) + "."
                                                    + Convert.ToString(Receivebytes[index + 2]) + "."
                                                    + Convert.ToString(Receivebytes[index + 3]); break;
                                        case 5: IPResponse = "CNAME"; break;
                                        case 6: IPResponse = "SOA"; break;
                                    }
                                    //StatusBoxPrint("DNS Answer: " + mo.URLNameStart + "." + mo.DomainName + " = " + IPResponse);

                                    if (!canrun)
                                        return;
                                    if (j % 20 == 0 && j!=0 && canrun && chckBox_strs.Checked || Convert.ToInt32(textBox_strs.Text)<20 || j==1)
                                    {


                                        // Find the URL entry in the list
                                        yours mi = new yours();

                                        mi.IPResponse = IPResponse;
                                        mi.DeltaTime = DeltaTime;
                                        mi.TransactionDNS = TransactionDNS;
                                        mi.i = i;
                                        mi.URLNameStart = URLNameStart;
                                        mi.DomainName = DomainName;
                                        mi.URLNamescount = mo.URLNamescount;
                                        if (ResultView.InvokeRequired)
                                        {
                                            changeListViewItems my = new changeListViewItems(_changeListViewItems);
                                            ResultView.Invoke(my, mi);

                                        }
                                        else
                                        {
                                            _changeListViewItems(mi);
                                        }
                                    }
                                   
                                }

                                if (!canrun)
                                    return;
                            }

                            // close the socket

                            DNSsocket.Close();

                            // mo._doneEvent[i].Set();
                            if (counter == 0 && canrun)
                            {
                                URLNameStart = mo.URLNames[i].Substring(0, mo.URLNames[i].IndexOf("."));
                                DomainName = mo.URLNames[i].Substring(mo.URLNames[i].IndexOf(".") + 1, mo.URLNames[i].Length - mo.URLNames[i].IndexOf(".") - 1);
                                IPEndPoint dnsEP2 = new IPEndPoint(IPAddress.Parse(mo.DNSAddress2), IPPort);
                                Sendbytes = new byte[256];
                                StartTime = DateTime.Now.Ticks;
                                DNSsocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
                                DNSsocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, DNSReceiveTimeout);
                                QueryString = TransactionID2 + TypeString + (char)URLNameStart.Length + URLNameStart + (char)DomainName.Length + DomainName + TrailerString;
                                Sendbytes = Encoding.ASCII.GetBytes(QueryString);
                                DNSsocket.SendTo(Sendbytes, Sendbytes.Length, SocketFlags.None, dnsEP2);
                                counter++;
                                goto second;
                            }
                            if (!canrun)
                                return;


                        }
                        catch (Exception e)
                        {
                            _StatusBoxPrint status = new _StatusBoxPrint(StatusBoxPrint);
                            StatusBox.Invoke(status, e.Message);
                            if (counter == 0 && canrun)
                            {
                                counter++;
                                goto third;
                            }
                            if (!canrun)
                                return;

                        }
                    }

                }
                else
                {
                    mine mo = (mine)me;
                    int i = mo.index;
                    string QueryString;
                    const string TransactionID1 = "Q1"; // Use transaction ID of Q1 and Q2 to identify our packet and DNS
                    const string TransactionID2 = "Q2";
                    const string TypeString = "\u0001" + "\u0000" + "\u0000" + "\u0001" + "\u0000" + "\u0000" + "\u0000" + "\u0000" + "\u0000" + "\u0000";
                    const string TrailerString = "\u0000" + "\u0000" + "\u0001" + "\u0000" + "\u0001";
                    int URLNameStartLength, DomainNameLength, index, TransactionDNS;
                    long StopTime;
                    string DeltaTime;
                    string ReceiveString, IPResponse;
                    string URLNameStart , DomainName;
                    const int IPPort = 53;
                    byte[] Receivebytes;
                    Socket DNSsocket;
                    byte[] Sendbytes;
                    Receivebytes = new byte[512];
                    
                        const int DNSReceiveTimeout = 5000;
                    fourth:

                        if (!canrun)
                            return;
                        try
                        {

                        Receivebytes = new byte[512];

                        long StartTime;
                        if (counter == 1)
                        {
                            URLNameStart = mo.URLNames[i].Substring(0, mo.URLNames[i].IndexOf("."));
                            DomainName = mo.URLNames[i].Substring(mo.URLNames[i].IndexOf(".") + 1, mo.URLNames[i].Length - mo.URLNames[i].IndexOf(".") - 1);
                            IPEndPoint dnsEP2 = new IPEndPoint(IPAddress.Parse(mo.DNSAddress2), IPPort);
                            Sendbytes = new byte[256];
                            StartTime = DateTime.Now.Ticks;
                            DNSsocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
                            DNSsocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, DNSReceiveTimeout);
                            QueryString = TransactionID2 + TypeString + (char)URLNameStart.Length + URLNameStart + (char)DomainName.Length + DomainName + TrailerString;
                            Sendbytes = Encoding.ASCII.GetBytes(QueryString);
                            DNSsocket.SendTo(Sendbytes, Sendbytes.Length, SocketFlags.None, dnsEP2);
                        }




                        // Build the query 
                        else
                        {
                            StartTime = DateTime.Now.Ticks;
                            DNSsocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
                            DNSsocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, DNSReceiveTimeout);


                            Sendbytes = new byte[256];

                            URLNameStart = mo.URLNames[i].Substring(0, mo.URLNames[i].IndexOf("."));
                            DomainName = mo.URLNames[i].Substring(mo.URLNames[i].IndexOf(".") + 1, mo.URLNames[i].Length - mo.URLNames[i].IndexOf(".") - 1);
                            IPEndPoint dnsEP1 = new IPEndPoint(IPAddress.Parse(mo.DNSAddress1), IPPort);
                            QueryString = TransactionID1 + TypeString + (char)URLNameStart.Length + URLNameStart + (char)DomainName.Length + DomainName + TrailerString;
                            Sendbytes = Encoding.ASCII.GetBytes(QueryString);
                            DNSsocket.SendTo(Sendbytes, Sendbytes.Length, SocketFlags.None, dnsEP1);
                        }

                            // send the same message to both DNS servers except for the transaction ID


                            // wait for a response up to timeout
                    second:
                        DNSsocket.Receive(Receivebytes);


                        // make sure the message returned is ours
                        if (Receivebytes[0] == Sendbytes[0] && (Receivebytes[1] == 0x31) || (Receivebytes[1] == 0x32))
                        {
                            if (Receivebytes[2] == 0x81 && Receivebytes[3] == 0x80)
                            {
                                // Get the time now
                                StopTime = DateTime.Now.Ticks;
                                DeltaTime = Convert.ToString((double)(StopTime - StartTime) / 10000000);

                                // Decode the answers
                                // Find the URL that was returned
                                TransactionDNS = Receivebytes[1];
                                ReceiveString = Encoding.ASCII.GetString(Receivebytes);
                                index = 12;
                                URLNameStartLength = Receivebytes[index];
                                index++;
                                URLNameStart = ReceiveString.Substring(index, URLNameStartLength);
                                index = index + URLNameStartLength;
                                DomainNameLength = Receivebytes[index];
                                index++;
                                DomainName = ReceiveString.Substring(index, DomainNameLength);
                                index = index + DomainNameLength;
                                index = index + 8;

                                // Get the record type
                                int ResponseType = Receivebytes[index];
                                index = index + 9;

                                // Get the IP address if applicable
                                IPResponse = "";
                                switch (ResponseType)
                                {
                                    case 1: IPResponse = Convert.ToString(Receivebytes[index]) + "."
                                                + Convert.ToString(Receivebytes[index + 1]) + "."
                                                + Convert.ToString(Receivebytes[index + 2]) + "."
                                                + Convert.ToString(Receivebytes[index + 3]); break;
                                    case 5: IPResponse = "CNAME"; break;
                                    case 6: IPResponse = "SOA"; break;
                                }
                                //StatusBoxPrint("DNS Answer: " + mo.URLNameStart + "." + mo.DomainName + " = " + IPResponse);

                                if (!canrun)
                                    return;
                                // Find the URL entry in the list
                                yours mi = new yours();

                                mi.IPResponse = IPResponse;
                                mi.DeltaTime = DeltaTime;
                                mi.TransactionDNS = TransactionDNS;
                                mi.i = i;
                                mi.URLNameStart = URLNameStart;
                                mi.DomainName = DomainName;
                                mi.URLNamescount = mo.URLNamescount;
                                if (ResultView.InvokeRequired)
                                {
                                    changeListViewItems my = new changeListViewItems(_changeListViewItems);
                                    ResultView.Invoke(my, mi);
                                    Application.DoEvents();

                                }
                                else
                                {
                                    _changeListViewItems(mi);
                                }
                                
                            }

                        }

                        // close the socket

                        DNSsocket.Close();


                        // mo._doneEvent[i].Set();
                        if (counter == 0 && canrun)
                        {
                            URLNameStart = mo.URLNames[i].Substring(0, mo.URLNames[i].IndexOf("."));
                            DomainName = mo.URLNames[i].Substring(mo.URLNames[i].IndexOf(".") + 1, mo.URLNames[i].Length - mo.URLNames[i].IndexOf(".") - 1);
                            IPEndPoint dnsEP2 = new IPEndPoint(IPAddress.Parse(mo.DNSAddress2), IPPort);
                            Sendbytes = new byte[256];
                            StartTime = DateTime.Now.Ticks;
                            DNSsocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
                            DNSsocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, DNSReceiveTimeout);
                            QueryString = TransactionID2 + TypeString + (char)URLNameStart.Length + URLNameStart + (char)DomainName.Length + DomainName + TrailerString;
                            Sendbytes = Encoding.ASCII.GetBytes(QueryString);
                            DNSsocket.SendTo(Sendbytes, Sendbytes.Length, SocketFlags.None, dnsEP2);
                            counter++;
                            goto second;
                        }


                    }

                    catch (Exception e)
                    {
                        _StatusBoxPrint status = new _StatusBoxPrint(StatusBoxPrint);
                        StatusBox.Invoke(status, e.Message);
                        if (counter == 0 && canrun)
                        {
                            counter++;
                            goto fourth;
                        }

                        if (!canrun)
                            return;

                    }
                }
            }
            catch (Exception e)
            {
                _StatusBoxPrint status = new _StatusBoxPrint(StatusBoxPrint);
                StatusBox.Invoke(status, e.Message);

                if (!canrun)
                    return;

            }
            Interlocked.Decrement(ref globalcounter);

            if (Interlocked.Equals(globalcounter, 0))
            {

                changeButtonsstate ch = new changeButtonsstate(_changeButtonsstate);
                Testbutton.Invoke(ch);
                changeButtonsstatestop chs = new changeButtonsstatestop(_changeButtonsstatestop);
                btn_stop.Invoke(chs);
                //changelabel_idle chl = new changelabel_idle(_changelabel_idle);
                //label_idle.Invoke(chl, "ide");
                label_idle.Text = "Idle";
            }
            
        }
        private delegate void changelabel_idle(object obj);
        private void _changelabel_idle(object obj)
        {
            string tmp = (string)obj;
            label_idle.Text = tmp;
        }
        private delegate void changeButtonsstate();
        private void _changeButtonsstate()
        {

            Testbutton.Enabled = true;
            Testbutton.Visible = true;
        }
        private delegate void changeButtonsstatestop();
        private void _changeButtonsstatestop()
        {

            btn_stop.Enabled = false;
            btn_stop.Visible = false;
        }
        private delegate void changeListViewItems(object obj);
        private void _changeListViewItems(object obj)
        {

            Application.DoEvents();
            if (!canrun)
                return;
            yours mo = (yours)obj;
            string DeltaTime = mo.DeltaTime;
            string sDeltaTime;
            for (int i = 0; i < mo.URLNamescount; i++)
            {
                if (ResultView.Items[i].Text == mo.URLNameStart + "." + mo.DomainName)
                {
                    Application.DoEvents();
                    switch (mo.TransactionDNS)
                    {
                        case 0x31:
                            ResultView.Items[i].SubItems[1].Text = Convert.ToString(mo.IPResponse);
                            sDeltaTime = Convert.ToString(DeltaTime);
                            if (sDeltaTime.Length > 5) ResultView.Items[i].SubItems[2].Text = sDeltaTime.Substring(0, 5);
                            else ResultView.Items[i].SubItems[2].Text = sDeltaTime;
                            ResultView.Items[i].ForeColor = System.Drawing.Color.Red;
                            //ResultView.EnsureVisible(i);                            
                            Application.DoEvents();
                            ResultView.Update();
                            Application.DoEvents();
                            ResultView.Items[i].ForeColor = System.Drawing.Color.Black;
                            break;

                        case 0x32:
                            ResultView.Items[i].SubItems[3].Text = Convert.ToString(mo.IPResponse);
                            sDeltaTime = Convert.ToString(DeltaTime);
                            if (sDeltaTime.Length > 5) ResultView.Items[i].SubItems[4].Text = sDeltaTime.Substring(0, 5);
                            else ResultView.Items[i].SubItems[4].Text = sDeltaTime;
                            ResultView.Items[i].ForeColor = System.Drawing.Color.Red;
                            //ResultView.EnsureVisible(i);
                            Application.DoEvents();
                            ResultView.Update();
                            Application.DoEvents();
                            ResultView.Items[i].ForeColor = System.Drawing.Color.Black;
                            break;
                    }
                }
            }
        }
	
			private void StatusBox_TextChanged(object sender, System.EventArgs e)
		{
			StatusBox.TopIndex=StatusBox.Items.Count;
			StatusBox.Update();
		}
        private delegate void _StatusBoxPrint(object obj);
		private void StatusBoxPrint(object obj)
		{
            if (canrun)
            {
                string LogText = (string)obj;
                StatusBox.Items.Add(DateTime.Now + "  " + LogText);
                StatusBox.TopIndex = StatusBox.Items.Count - 1;
                if (StatusBox.Items.Count > 5000)
                {
                    StatusBox.Items.RemoveAt(0);
                }
                StatusBox.Update();
            }
		}
		private void DNSAvg1Box_TextChanged(object sender, System.EventArgs e)
		{
		
		}

		private void DNSAvg2Box_TextChanged(object sender, System.EventArgs e)
		{
		
		}

		private void DNSBox1_TextChanged(object sender, System.EventArgs e)
		{
			DNS1=DNSBox1.Text;
		}

		private void DNSBox2_TextChanged(object sender, System.EventArgs e)
		{
			DNS2=DNSBox2.Text;
		}

	
		private void ResultBox_SelectedIndexChanged(object sender, System.EventArgs e)
		{
		
		}

		private void HTTPProxyBox_TextChanged(object sender, System.EventArgs e)
		{
			if (HTTPProxyBox.Text != "")
			{
				WebRequest.DefaultWebProxy.GetProxy( new System.Uri(HTTPProxyBox.Text));
			}
			else
			{
				WebRequest.DefaultWebProxy.GetProxy(new System.Uri(WebRequest.GetSystemWebProxy().ToString()));
			}
		}

        private void DNSTester_Load(object sender, EventArgs e)
        {

        }

        private void chckBox_strs_CheckedChanged(object sender, EventArgs e)
        {
            CheckBox tmp = (CheckBox)sender;
            if (tmp.Checked)
            {
                textBox_strs.Enabled = true;
            }
            else
                textBox_strs.Enabled = false;

        }

        private void btn_stop_Click(object sender, EventArgs e)
        {
            canrun = false;
            Testbutton.Enabled = true;
            Testbutton.Visible = true;
            btn_stop.Enabled = false;
            btn_stop.Visible = false;
            label_idle.Text = "Idle";
        }

        private void label_idle_Click(object sender, EventArgs e)
        {

        }

        private void toolStripStatusLabel1_Click(object sender, EventArgs e)
        {

        }
	}
    public class mine
    {
        public mine(string[] URLNames, int URLNamescount, string DNSAddress1, string DNSAddress2, int index)
        {
            this.DNSAddress1 = DNSAddress1;
            this.DNSAddress2 = DNSAddress2;
            this.URLNames = URLNames;
            this.URLNamescount = URLNamescount;
            this.index = index;

        }
        public string[] URLNames;
        public int URLNamescount;
        public string DNSAddress1, DNSAddress2;
        public int index;
    }
    public class yours
    {
        public yours()
        {
        }
        public string IPResponse, DeltaTime, URLNameStart, DomainName;
        public int TransactionDNS, i, URLNamescount;
    }
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Student Isfahan University of Technology (IUT)
Iran (Islamic Republic of) Iran (Islamic Republic of)
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions