+ Reply to Thread
Results 1 to 8 of 8

Thread: Creating a Pinging tool like CMD Ping

  1. #1
    Junior Member
    Join Date
    Feb 2012
    Posts
    12

    Cool Creating a Pinging tool like CMD Ping

    Hey Guys , today i created a custom Ping utility , it took me 5 hours
    It is exactly the same as CMD , it might miss some things but the common things are exist , like selecting buffer size and the Looping

    Covered Points :
    ----------------
    - CTRL + C interruption
    - Most of Pinging commands
    - Works faster than the CMD

    *** I`ll post the code into separate posts because it is so big. [JUST COPY EVERYTHING AND PASTE IT INTO Solution]
    *** If you can`t stand reading all that , my ADVICE : copy the code and paste into your Console Application and things will get much much clearer

    Here is the Full Commented Code :
    Code:
    using System;
    using System.Collections.Generic;
    using System.Text;
    using System.Net.NetworkInformation;
    using System.Management;
    using System.Runtime.InteropServices;
    using System.Threading;
    using System.Reflection;
    
    namespace Custom_Ping
    {
        class Program
        {
            #region GLOBAL VARS
            private static readonly Mutex mutex = new Mutex(true, Assembly.GetExecutingAssembly().GetName().CodeBase);
            private static bool _userRequestExit = false;
            private static bool _doIStop = false;
            static HandlerRoutine consoleHandler;
            #endregion
    
            [DllImport("Kernel32")]
            public static extern bool SetConsoleCtrlHandler(HandlerRoutine Handler, bool Add);
    
            // A delegate type to be used as the handler routine for SetConsoleCtrlHandler.
            public delegate bool HandlerRoutine(CtrlTypes CtrlType);
    
            // An enumerated type for the control messages sent to the handler routine.
            public enum CtrlTypes
            {
                CTRL_C_EVENT = 0,
                CTRL_BREAK_EVENT,
                CTRL_CLOSE_EVENT,
                CTRL_LOGOFF_EVENT = 5,
                CTRL_SHUTDOWN_EVENT
            }
    
            /// <summary>
            /// 
            /// </summary>
            /// <param name="ctrlType"></param>
            /// <returns></returns>
            private static bool ConsoleCtrlCheck(CtrlTypes ctrlType)
            {
                // Put your own handler here
                switch (ctrlType)
                {
                    case CtrlTypes.CTRL_C_EVENT:
                        _userRequestExit = true;
                        break;
                }
    
                return true;
            }
    
            /// <summary>
            /// Main entry point
            /// </summary>
            /// <param name="args"></param>
            /// <returns></returns>  
    
    
            int sucess = 0;
            int fail = 0;
            int minrtt = 0; // Min RTT
            int maxrtt = 0; // Max RTT
            int ttlrtt = 0; // Total RTT
            int avgrtt = 0; // Average RTT
            int sent = 0;
            int loss = 0;
    
            int bytes1 = 0;
      
            List<int> list = new List<int>();
    		
    		// Entry Point
            static void Main(string[] args)
            {
                Program p = new Program();
                p.cmdbeing1();
                p.MainApplication();
            }
    Last edited by petervc; 04-28-2012 at 05:47 PM.

  2. #2
    Junior Member
    Join Date
    Feb 2012
    Posts
    12
    Code:
            private void MainApplication()
            {
                //save a reference so it does not get GC'd
                consoleHandler = new HandlerRoutine(ConsoleCtrlCheck);
    
                //set our handler here that will trap exit
                SetConsoleCtrlHandler(consoleHandler, true);
    
                Program p = new Program();
                p.cmdbegin2();
                for (int i = 0; i < 1000; i++)
                {
                    try
                    {
    					// read the input as a command line
                        string commandline = Console.ReadLine();
    
                        // ping -h
                        #region
                        if (commandline.Contains("-h") && commandline.Contains("ping"))
                        {
                            p.help();
                            p.cmdbegin2();
                        }
                        #endregion
                        // -t -f -l
                        #region
                        else if (commandline.Contains("ping") && commandline.Contains("-t") && commandline.Contains("-f") && commandline.Contains("-l"))
                        {
                            string[] splitwebsite = commandline.Split(' ');
    
                            List<string> linelist = new List<string>();
    
                            foreach (string field in splitwebsite)
                            {
                                if (field != "ping" && field != "-t" && field != "-f" && field != "-l" && !field.Contains("."))
                                {
                                    linelist.Add(field);
                                }
                                else if (field != "ping" && field != "-t" && field != "-f" && field != "-l" && field.Contains("."))
                                {
                                    linelist.Add(field);
                                }
                            }
    
                            linelist.Sort();
    
                            foreach (var item in linelist)
                            {
                                if (item != "ping" && item != "-t" && item != "-f" && item != "-l" && !item.Contains("."))
                                {
                                    p.bytes1 = Convert.ToInt32(item);
                                }
                                else if (item != "ping" && item != "-t" && item != "-f" && item != "-l" && item.Contains("."))
                                {
                                    p._t_f_l(item);
                                }
                            }
                            p.cmdbegin2();
                        }
                        #endregion
    
                        // -t -l
                        #region
                        else if (commandline.Contains("ping") && commandline.Contains("-t") && !commandline.Contains("-f") && commandline.Contains("-l"))
                        {
                            string[] splitwebsite = commandline.Split(' ');
    
                            List<string> linelist = new List<string>();
    
                            foreach (string field in splitwebsite)
                            {
                                if (field != "ping" && field != "-t" && field != "-l" && !field.Contains("."))
                                {
                                    linelist.Add(field);
                                }
                                else if (field != "ping" && field != "-t" && field != "-l" && field.Contains("."))
                                {
                                    linelist.Add(field);
                                }
                            }
    
                            linelist.Sort();
    
                            foreach (var item in linelist)
                            {
                                if (item != "ping" && item != "-t" && item != "-l" && !item.Contains("."))
                                {
                                    p.bytes1 = Convert.ToInt32(item);
                                }
                                else if (item != "ping" && item != "-t" && item != "-l" && item.Contains("."))
                                {
                                    p._t_l(item);
                                }
                            }
                            p.cmdbegin2();
                        }
                        #endregion

  3. #3
    Junior Member
    Join Date
    Feb 2012
    Posts
    12
    Code:
                        // -f -l
                        #region
                        else if (commandline.Contains("ping") && !commandline.Contains("-t") && commandline.Contains("-f") && commandline.Contains("-l"))
                        {
                            string[] splitwebsite = commandline.Split(' ');
    
                            List<string> linelist = new List<string>();
    
                            foreach (string field in splitwebsite)
                            {
                                if (field != "ping" && field != "-f" && field != "-l" && !field.Contains("."))
                                {
                                    linelist.Add(field);
                                }
                                else if (field != "ping" && field != "-f" && field != "-l" && field.Contains("."))
                                {
                                    linelist.Add(field);
                                }
                            }
    
                            linelist.Sort();
    
                            foreach (var item in linelist)
                            {
                                if (item != "ping" && item != "-f" && item != "-l" && !item.Contains("."))
                                {
                                    p.bytes1 = Convert.ToInt32(item);
                                }
                                else if (item != "ping" && item != "-f" && item != "-l" && item.Contains("."))
                                {
                                    p._f_l(item);
                                }
                            }
                            p.cmdbegin2();
                        }
                        #endregion
    
                        // -l
                        #region
                        else if (commandline.Contains("ping") && !commandline.Contains("-t") && !commandline.Contains("-f") && commandline.Contains("-l"))
                        {
                            string[] splitwebsite = commandline.Split(' ');
    
                            List<string> linelist = new List<string>();
    
                            foreach (string field in splitwebsite)
                            {
                                if (field != "ping" && field != "-l" && !field.Contains("."))
                                {
                                    linelist.Add(field);
                                }
                                else if (field != "ping" && field != "-l" && field.Contains("."))
                                {
                                    linelist.Add(field);
                                }
                            }
    
                            linelist.Sort();
    
                            foreach (var item in linelist)
                            {
                                if (item != "ping" && item != "-l" && !item.Contains("."))
                                {
                                    p.bytes1 = Convert.ToInt32(item);
                                }
                                else if (item != "ping" && item != "-l" && item.Contains("."))
                                {
                                    p._l(item);
                                }
                            }
                            p.cmdbegin2();
                        }
                        #endregion
    
                        // -t -f
                        #region
                        else if (commandline.Contains("ping") && commandline.Contains("-t") && commandline.Contains("-f") && !commandline.Contains("-l"))
                        {
                            string[] splitwebsite = commandline.Split(' ');
    
                            foreach (string field in splitwebsite)
                            {
                                if (field != "ping" && field != "-t" && field != "-f")
                                {
                                    p._t_f(field);
                                }
                            }
                            p.cmdbegin2();
                        }
                        // -t
                        else if (commandline.Contains("ping") && commandline.Contains("-t") && !commandline.Contains("-f") && !commandline.Contains("-l"))
                        {
                            string[] splitwebsite = commandline.Split(' ');
    
                            foreach (string field in splitwebsite)
                            {
                                if (field != "ping" && field != "-t")
                                {
                                    p._t(field);
                                }
                            }
                            p.cmdbegin2();
                        }
                        #endregion
    
                        // -f
                        #region
                        else if (commandline.Contains("ping") && !commandline.Contains("-t") && commandline.Contains("-f") && !commandline.Contains("-l"))
                        {
                            string[] splitwebsite = commandline.Split(' ');
    
                            foreach (string field in splitwebsite)
                            {
                                if (field != "ping" && field != "-f")
                                {
                                    p._f(field);
                                }
                            }
                            p.cmdbegin2();
                        }
                        #endregion
    
                        // ping
                        #region
                        else if (commandline.Contains("ping") && !commandline.Contains("-t") && !commandline.Contains("-f") && !commandline.Contains("-l"))
                        {
                            string[] splitwebsite = commandline.Split(' ');
    
                            foreach (string field in splitwebsite)
                            {
                                if (field != "ping" && field != "-f")
                                {
                                    p.ping(field);
                                }
                            }
                            p.cmdbegin2();
                        }
                        #endregion
    
                        // else out
                        #region
                        else if (!commandline.Contains("ping"))
                        {
                            //int count=0;
    
                            string[] splitwebsite = commandline.Split(' ');
    
                            foreach (string field in splitwebsite)
                            {
                                Console.WriteLine("'{0}", field + "'" + " is not recognized as an internal or external website,operable program or batch file.");
                                break;
                            }
                            p.cmdbegin2();
                        }
                        #endregion
                    }
                    catch (NullReferenceException)
                    {
                        MainApplication();
                    }
                }
            }

  4. #4
    Junior Member
    Join Date
    Feb 2012
    Posts
    12
    Code:
            private void cmdbeing1()
            {
    			// Same Header text inside CMD
                Console.WriteLine("Microsoft Windows [Version 6.1.7600]\nCopyright (c) 2009 Microsoft Corporation.  All rights reserved.");
            }
            private void cmdbegin2()
            {
    			// The Old way i used to retrieve the Username of the computer
                /*SelectQuery query = new SelectQuery("Win32_UserAccount");
                ManagementObjectSearcher search4names = new ManagementObjectSearcher(query);
    
                foreach (ManagementObject getnames in search4names.Get())
                {
                    string rule;
                    rule = getnames["Name"].ToString();
                    // we will exclude these users as they are system users
                    if (rule == "Administrator" || rule == "Guest" || rule == "HomeGroupUser$" || rule == "Default" || rule == "__vmware_user__")
                    {
                    }
                    else
                    {
                        Console.Write("\nC:\\Users\\" + rule + ">");
                        break;
                    }
                }*/
    			
    			// The more easy WAY!!!!
                Console.Write("\nC:\\Users\\" + System.Environment.UserName.ToString() + ">");
            }
    		// Case ping xxxxx.com -t -f
            private void _t_f(string website)
            {
                Ping pingSender = new Ping();
    			// 32-bit of data
                string data = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
                byte[] buffer = Encoding.ASCII.GetBytes(data);
                int timeout = 10000;
    
                string address = "";
                try
                {
                    PingOptions options = new PingOptions(64, true);
                    for (int i = 0; i < 10; i++)
                    {
                        try
                        {
                            PingReply send0 = pingSender.Send(website, timeout, buffer, options);
                            Console.WriteLine("\nPinging {0} [{1}] With {2} bytes of data :", website, send0.Address.ToString(), send0.Buffer.Length);
                            address = send0.Address.ToString();
                            break;
                        }
                        catch (NullReferenceException)
                        {
                        }
                    }
    
                    while (true)
                    {
    					// in case user pressed CTRL + C to quit Loop
                        if (_userRequestExit)
                        {
                            _doIStop = true;
                            break;
                        }
                        else
                        {
                            PingReply reply = pingSender.Send(website, timeout, buffer, options);
    
                            if (reply.Status == IPStatus.Success)
                            {
                                Console.WriteLine("Reply from {0}: Bytes {1} time={2} TTL={3}", reply.Address.ToString(), reply.Buffer.Length, reply.RoundtripTime, reply.Options.Ttl);
                                sucess++;
                                sent++;
                                ttlrtt += Convert.ToInt16(reply.RoundtripTime);
                                
                                int time = Convert.ToInt16(reply.RoundtripTime);
                                list.Add(time);
                            }
                            else
                            {
                                Console.WriteLine("Request timed out.");
                                fail++;
                                sent++;
                                if (!list.Contains(0))
                                list.Add(0);
                            }
                        }
                    }
                    loss = (fail / sent);
                    avgrtt = ttlrtt / sent;
                    list.Sort();
                    if (list[0] == 0)
                    {
                        minrtt = list[1];
                    }
                    else
                    { minrtt = list[0]; }
                    maxrtt = list[list.Count - 1];
                    Console.WriteLine("\nPing statistics for {0}:\n    Packets: Sent = {1}, Received = {2}, Lost = {3} ({4}% loss),\nApproximate round trip times in milli-seconds:\n    Minimum = {5}ms, Maximum = {6}ms, Average = {7}ms", address, sent, sucess, fail, loss * 100, minrtt, maxrtt, avgrtt);
                    _doIStop = false; _userRequestExit = false; sucess = 0; sent = 0; ttlrtt = 0; list.Clear(); fail = 0; loss = 0; avgrtt = 0; minrtt = 0; maxrtt = 0;
                }
                catch (Exception ee)
                {
                    Console.WriteLine("Ping request could not find host {0} ", website + ".Please check the name and try again.");
                    //Console.WriteLine(ee.ToString());
                }
            }

  5. #5
    Junior Member
    Join Date
    Feb 2012
    Posts
    12
    Code:
    		// Case ping xxxxx.com -t
            private void _t(string website)
            {
                Ping pingSender = new Ping();
                string data = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
                byte[] buffer = Encoding.ASCII.GetBytes(data);
                int timeout = 10000;
    
                string address = "";
                try
                {
                    PingOptions options = new PingOptions(64, false);
                    for (int i = 0; i < 10; i++)
                    {
                        try
                        {
                            PingReply send0 = pingSender.Send(website, timeout, buffer, options);
                            Console.WriteLine("\nPinging {0} [{1}] With {2} bytes of data :", website, send0.Address.ToString(), send0.Buffer.Length);
                            address = send0.Address.ToString();
                            break;
                        }
                        catch (NullReferenceException)
                        {
                        }
                    }
    
                    while (true)
                    {
                        if (_userRequestExit)
                        {
                            _doIStop = true;
                            break;
                        }
                        else
                        {
                            PingReply reply = pingSender.Send(website, timeout, buffer, options);
    
                            if (reply.Status == IPStatus.Success)
                            {
                                Console.WriteLine("Reply from {0}: Bytes {1} time={2} TTL={3}", reply.Address.ToString(), reply.Buffer.Length, reply.RoundtripTime, reply.Options.Ttl);
                                sucess++;
                                sent++;
                                ttlrtt += Convert.ToInt16(reply.RoundtripTime);
    
                                int time = Convert.ToInt16(reply.RoundtripTime);
                                list.Add(time);
                            }
                            else
                            {
                                Console.WriteLine("Request timed out.");
                                fail++;
                                sent++;
                                if (!list.Contains(0))
                                    list.Add(0);
                            }
                        }
                    }
                    loss = (fail / sent);
                    avgrtt = ttlrtt / sent;
                    list.Sort();
                    if (list[0] == 0)
                    {
                        minrtt = list[1];
                    }
                    else
                    { minrtt = list[0]; }
                    maxrtt = list[list.Count - 1];
                    Console.WriteLine("\nPing statistics for {0}:\n    Packets: Sent = {1}, Received = {2}, Lost = {3} ({4}% loss),\nApproximate round trip times in milli-seconds:\n    Minimum = {5}ms, Maximum = {6}ms, Average = {7}ms", address, sent, sucess, fail, loss * 100, minrtt, maxrtt, avgrtt);
                    _doIStop = false; _userRequestExit = false; sucess = 0; sent = 0; ttlrtt = 0; list.Clear(); fail = 0; loss = 0; avgrtt = 0; minrtt = 0; maxrtt = 0;
                }
                catch (Exception ee)
                {
                    Console.WriteLine("Ping request could not find host {0} ", website + ".Please check the name and try again.");
                    //Console.WriteLine(ee.ToString());
                }
            }
    		// Case ping xxxxx.com -f
            private void _f(string website)
            {
                Ping pingSender = new Ping();
                string data = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
                byte[] buffer = Encoding.ASCII.GetBytes(data);
                int timeout = 10000;
    
                string address = "";
                try
                {
                    PingOptions options = new PingOptions(64, true);
                    for (int i = 0; i < 10; i++)
                    {
                        try
                        {
                            PingReply send0 = pingSender.Send(website, timeout, buffer, options);
                            Console.WriteLine("\nPinging {0} [{1}] With {2} bytes of data :", website, send0.Address.ToString(), send0.Buffer.Length);
                            address = send0.Address.ToString();
                            break;
                        }
                        catch (NullReferenceException)
                        {
                        }
                    }
    
                    for (int i = 0; i < 4;i++)
                    {
                        if (_userRequestExit)
                        {
                            _doIStop = true;
                            break;
                        }
                        else
                        {
                            PingReply reply = pingSender.Send(website, timeout, buffer, options);
    
                            if (reply.Status == IPStatus.Success)
                            {
                                Console.WriteLine("Reply from {0}: Bytes {1} time={2} TTL={3}", reply.Address.ToString(), reply.Buffer.Length, reply.RoundtripTime, reply.Options.Ttl);
                                sucess++;
                                sent++;
                                ttlrtt += Convert.ToInt16(reply.RoundtripTime);
    
                                int time = Convert.ToInt16(reply.RoundtripTime);
                                list.Add(time);
                            }
                            else
                            {
                                Console.WriteLine("Request timed out.");
                                fail++;
                                sent++;
                                if (!list.Contains(0))
                                    list.Add(0);
                            }
                        }
                    }
                    loss = (fail / sent);
                    avgrtt = ttlrtt / sent;
                    list.Sort();
                    if (list[0] == 0)
                    {
                        minrtt = list[1];
                    }
                    else
                    { minrtt = list[0]; }
                    maxrtt = list[list.Count - 1];
                    Console.WriteLine("\nPing statistics for {0}:\n    Packets: Sent = {1}, Received = {2}, Lost = {3} ({4}% loss),\nApproximate round trip times in milli-seconds:\n    Minimum = {5}ms, Maximum = {6}ms, Average = {7}ms", address, sent, sucess, fail, loss * 100, minrtt, maxrtt, avgrtt);
                    _doIStop = false; _userRequestExit = false; sucess = 0; sent = 0; ttlrtt = 0; list.Clear(); fail = 0; loss = 0; avgrtt = 0; minrtt = 0; maxrtt = 0;
                }
                catch (Exception ee)
                {
                    Console.WriteLine("Ping request could not find host {0} ", website + ".Please check the name and try again.");
                    //Console.WriteLine(ee.ToString());
                }
            }

  6. #6
    Junior Member
    Join Date
    Feb 2012
    Posts
    12
    Code:
    		// Case ping xxxxx.com only
            private void ping(string website)
            {
                Ping pingSender = new Ping();
                string data = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
                byte[] buffer = Encoding.ASCII.GetBytes(data);
                int timeout = 10000;
    
                string address = "";
                try
                {
                    PingOptions options = new PingOptions(64, false);
                    for (int i = 0; i < 10; i++)
                    {
                        try
                        {
                            PingReply send0 = pingSender.Send(website, timeout, buffer, options);
                            Console.WriteLine("\nPinging {0} [{1}] With {2} bytes of data :", website, send0.Address.ToString(), send0.Buffer.Length);
                            address = send0.Address.ToString();
                            break;
                        }
                        catch (NullReferenceException)
                        {
                        }
                    }
    
                    for (int i = 0; i < 4; i++)
                    {
                        if (_userRequestExit)
                        {
                            _doIStop = true;
                            break;
                        }
                        else
                        {
                            PingReply reply = pingSender.Send(website, timeout, buffer, options);
    
                            if (reply.Status == IPStatus.Success)
                            {
                                Console.WriteLine("Reply from {0}: Bytes {1} time={2} TTL={3}", reply.Address.ToString(), reply.Buffer.Length, reply.RoundtripTime, reply.Options.Ttl);
                                sucess++;
                                sent++;
                                ttlrtt += Convert.ToInt16(reply.RoundtripTime);
    
                                int time = Convert.ToInt16(reply.RoundtripTime);
                                list.Add(time);
                            }
                            else
                            {
                                Console.WriteLine("Request timed out.");
                                fail++;
                                sent++;
                                if (!list.Contains(0))
                                    list.Add(0);
                            }
                        }
                    }
                    loss = (fail / sent);
                    avgrtt = ttlrtt / sent;
                    list.Sort();
                    if (list[0] == 0)
                    {
                        minrtt = list[1];
                    }
                    else
                    { minrtt = list[0]; }
                    maxrtt = list[list.Count - 1];
                    Console.WriteLine("\nPing statistics for {0}:\n    Packets: Sent = {1}, Received = {2}, Lost = {3} ({4}% loss),\nApproximate round trip times in milli-seconds:\n    Minimum = {5}ms, Maximum = {6}ms, Average = {7}ms", address, sent, sucess, fail, loss * 100, minrtt, maxrtt, avgrtt);
                    _doIStop = false; _userRequestExit = false; sucess = 0; sent = 0; ttlrtt = 0; list.Clear(); fail = 0; loss = 0; avgrtt = 0; minrtt = 0; maxrtt = 0;
                }
                catch (Exception ee)
                {
                    Console.WriteLine("Ping request could not find host {0} ", website + ".Please check the name and try again.");
                    //Console.WriteLine(ee.ToString());
                }
            }
    		// Case ping xxxxx.com -t -f -l
            private void _t_f_l(string website)
            {
                //StringBuilder data = new StringBuilder();
                string data = "";
                for (int i = 0; i < bytes1; i++)
                { /*data.Append("a");*/ data += "a"; }
                Ping pingSender = new Ping();
                byte[] buffer = Encoding.ASCII.GetBytes(data);
                //byte[] buffer = Encoding.ASCII.GetBytes(data.ToString());
                int timeout = 10000;
                
                string address = "";
                try
                {
                    PingOptions options = new PingOptions(64, true);
                    for (int i = 0; i < 10; i++)
                    {
                        try
                        {
                            PingReply send0 = pingSender.Send(website, timeout, buffer, options);
                            Console.WriteLine("\nPinging {0} [{1}] With {2} bytes of data :", website, send0.Address.ToString(), send0.Buffer.Length);
                            address = send0.Address.ToString();
                            break;
                        }
                        catch (NullReferenceException)
                        {
                        }
                    }
    
                    while (true)
                    {
                        if (_userRequestExit)
                        {
                            _doIStop = true;
                            break;
                        }
                        else
                        {
                            PingReply reply = pingSender.Send(website, timeout, buffer, options);
    
                            if (reply.Status == IPStatus.Success)
                            {
                                Console.WriteLine("Reply from {0}: Bytes {1} time={2} TTL={3}", reply.Address.ToString(), reply.Buffer.Length, reply.RoundtripTime, reply.Options.Ttl);
                                sucess++;
                                sent++;
                                ttlrtt += Convert.ToInt16(reply.RoundtripTime);
    
                                int time = Convert.ToInt16(reply.RoundtripTime);
                                list.Add(time);
                            }
                            else
                            {
                                Console.WriteLine("Request timed out.");
                                fail++;
                                sent++;
                                if (!list.Contains(0))
                                    list.Add(0);
                            }
                        }
                    }
                    loss = (fail / sent);
                    avgrtt = ttlrtt / sent;
                    list.Sort();
                    if (list.Count > 1)
                    {
                        if (list[0] == 0)
                        {
                            minrtt = list[1];
                        }
                        else
                        { minrtt = list[0]; }
    
                        maxrtt = list[list.Count - 1];
                    }
                    Console.WriteLine("\nPing statistics for {0}:\n    Packets: Sent = {1}, Received = {2}, Lost = {3} ({4}% loss),\nApproximate round trip times in milli-seconds:\n    Minimum = {5}ms, Maximum = {6}ms, Average = {7}ms", address, sent, sucess, fail, loss * 100, minrtt, maxrtt, avgrtt);
                    _doIStop = false; _userRequestExit = false; sucess = 0; sent = 0; ttlrtt = 0; list.Clear(); fail = 0; loss = 0; avgrtt = 0; minrtt = 0; maxrtt = 0;
                }
                catch (Exception ee)
                {
                    //Console.WriteLine("Ping request could not find host {0} ", website + ".Please check the name and try again.");
                    Console.WriteLine(ee.ToString());
                }
            }

  7. #7
    Junior Member
    Join Date
    Feb 2012
    Posts
    12
    Code:
    		// Case ping xxxxx.com -t -l
            private void _t_l(string website)
            {
                //StringBuilder data = new StringBuilder();
                string data = "";
                for (int i = 0; i < bytes1; i++)
                { /*data.Append("a");*/ data += "a"; }
                Ping pingSender = new Ping();
                byte[] buffer = Encoding.ASCII.GetBytes(data);
                //byte[] buffer = Encoding.ASCII.GetBytes(data.ToString());
                int timeout = 10000;
    
                string address = "";
                try
                {
                    PingOptions options = new PingOptions(64, false);
                    for (int i = 0; i < 10; i++)
                    {
                        try
                        {
                            PingReply send0 = pingSender.Send(website, timeout, buffer, options);
                            Console.WriteLine("\nPinging {0} [{1}] With {2} bytes of data :", website, send0.Address.ToString(), send0.Buffer.Length);
                            address = send0.Address.ToString();
                            break;
                        }
                        catch (NullReferenceException)
                        {
                        }
                    }
    
                    while (true)
                    {
                        if (_userRequestExit)
                        {
                            _doIStop = true;
                            break;
                        }
                        else
                        {
                            PingReply reply = pingSender.Send(website, timeout, buffer, options);
    
                            if (reply.Status == IPStatus.Success)
                            {
                                Console.WriteLine("Reply from {0}: Bytes {1} time={2} TTL={3}", reply.Address.ToString(), reply.Buffer.Length, reply.RoundtripTime, reply.Options.Ttl);
                                sucess++;
                                sent++;
                                ttlrtt += Convert.ToInt16(reply.RoundtripTime);
    
                                int time = Convert.ToInt16(reply.RoundtripTime);
                                list.Add(time);
                            }
                            else
                            {
                                Console.WriteLine("Request timed out.");
                                fail++;
                                sent++;
                                if (!list.Contains(0))
                                    list.Add(0);
                            }
                        }
                    }
                    loss = (fail / sent);
                    avgrtt = ttlrtt / sent;
                    list.Sort();
                    if (list.Count > 1)
                    {
                        if (list[0] == 0)
                        {
                            minrtt = list[1];
                        }
                        else
                        { minrtt = list[0]; }
    
                        maxrtt = list[list.Count - 1];
                    }
                    Console.WriteLine("\nPing statistics for {0}:\n    Packets: Sent = {1}, Received = {2}, Lost = {3} ({4}% loss),\nApproximate round trip times in milli-seconds:\n    Minimum = {5}ms, Maximum = {6}ms, Average = {7}ms", address, sent, sucess, fail, loss * 100, minrtt, maxrtt, avgrtt);
                    _doIStop = false; _userRequestExit = false; sucess = 0; sent = 0; ttlrtt = 0; list.Clear(); fail = 0; loss = 0; avgrtt = 0; minrtt = 0; maxrtt = 0;
                }
                catch (Exception ee)
                {
                    //Console.WriteLine("Ping request could not find host {0} ", website + ".Please check the name and try again.");
                    Console.WriteLine(ee.ToString());
                }
            }
    		// Case ping xxxxx.com -f -l
            private void _f_l(string website)
            {
                string data = "";
                for (int i = 0; i < bytes1; i++)
                { data += "a"; }
                Ping pingSender = new Ping();
                byte[] buffer = Encoding.ASCII.GetBytes(data);
                int timeout = 10000;
    
                string address = "";
                try
                {
                    PingOptions options = new PingOptions(64, true);
                    for (int i = 0; i < 10; i++)
                    {
                        try
                        {
                            PingReply send0 = pingSender.Send(website, timeout, buffer, options);
                            Console.WriteLine("\nPinging {0} [{1}] With {2} bytes of data :", website, send0.Address.ToString(), send0.Buffer.Length);
                            address = send0.Address.ToString();
                            break;
                        }
                        catch (NullReferenceException)
                        {
                        }
                    }
    
                    for (int i = 0; i < 4; i++)
                    {
                        if (_userRequestExit)
                        {
                            _doIStop = true;
                            break;
                        }
                        else
                        {
                            PingReply reply = pingSender.Send(website, timeout, buffer, options);
    
                            if (reply.Status == IPStatus.Success)
                            {
                                Console.WriteLine("Reply from {0}: Bytes {1} time={2} TTL={3}", reply.Address.ToString(), reply.Buffer.Length, reply.RoundtripTime, reply.Options.Ttl);
                                sucess++;
                                sent++;
                                ttlrtt += Convert.ToInt16(reply.RoundtripTime);
    
                                int time = Convert.ToInt16(reply.RoundtripTime);
                                list.Add(time);
                            }
                            else
                            {
                                Console.WriteLine("Request timed out.");
                                fail++;
                                sent++;
                                if (!list.Contains(0))
                                    list.Add(0);
                            }
                        }
                    }
                    loss = (fail / sent);
                    avgrtt = ttlrtt / sent;
                    list.Sort();
                    if (list[0] == 0)
                    {
                        minrtt = list[1];
                    }
                    else
                    { minrtt = list[0]; }
                    maxrtt = list[list.Count - 1];
                    Console.WriteLine("\nPing statistics for {0}:\n    Packets: Sent = {1}, Received = {2}, Lost = {3} ({4}% loss),\nApproximate round trip times in milli-seconds:\n    Minimum = {5}ms, Maximum = {6}ms, Average = {7}ms", address, sent, sucess, fail, loss * 100, minrtt, maxrtt, avgrtt);
                    _doIStop = false; _userRequestExit = false; sucess = 0; sent = 0; ttlrtt = 0; list.Clear(); fail = 0; loss = 0; avgrtt = 0; minrtt = 0; maxrtt = 0;
                }
                catch (Exception ee)
                {
                    Console.WriteLine("Ping request could not find host {0} ", website + ".Please check the name and try again.");
                    //Console.WriteLine(ee.ToString());
                }
            }

  8. #8
    Junior Member
    Join Date
    Feb 2012
    Posts
    12
    Code:
    		// Case ping xxxxx.com -l
            private void _l(string website)
            {
                string data = "";
                for (int i = 0; i < bytes1; i++)
                { data += "a"; }
                Ping pingSender = new Ping();
                byte[] buffer = Encoding.ASCII.GetBytes(data);
                int timeout = 10000;
    
                string address = "";
                try
                {
                    PingOptions options = new PingOptions(64, false);
                    for (int i = 0; i < 10; i++)
                    {
                        try
                        {
                            PingReply send0 = pingSender.Send(website, timeout, buffer, options);
                            Console.WriteLine("\nPinging {0} [{1}] With {2} bytes of data :", website, send0.Address.ToString(), send0.Buffer.Length);
                            address = send0.Address.ToString();
                            break;
                        }
                        catch (NullReferenceException)
                        {
                        }
                    }
    
                    for (int i = 0; i < 4; i++)
                    {
                        if (_userRequestExit)
                        {
                            _doIStop = true;
                            break;
                        }
                        else
                        {
                            PingReply reply = pingSender.Send(website, timeout, buffer, options);
    
                            if (reply.Status == IPStatus.Success)
                            {
                                Console.WriteLine("Reply from {0}: Bytes {1} time={2} TTL={3}", reply.Address.ToString(), reply.Buffer.Length, reply.RoundtripTime, reply.Options.Ttl);
                                sucess++;
                                sent++;
                                ttlrtt += Convert.ToInt16(reply.RoundtripTime);
    
                                int time = Convert.ToInt16(reply.RoundtripTime);
                                list.Add(time);
                            }
                            else
                            {
                                Console.WriteLine("Request timed out.");
                                fail++;
                                sent++;
                                if (!list.Contains(0))
                                    list.Add(0);
                            }
                        }
                    }
                    loss = (fail / sent);
                    avgrtt = ttlrtt / sent;
                    list.Sort();
                    if (list[0] == 0)
                    {
                        minrtt = list[1];
                    }
                    else
                    { minrtt = list[0]; }
                    maxrtt = list[list.Count - 1];
                    Console.WriteLine("\nPing statistics for {0}:\n    Packets: Sent = {1}, Received = {2}, Lost = {3} ({4}% loss),\nApproximate round trip times in milli-seconds:\n    Minimum = {5}ms, Maximum = {6}ms, Average = {7}ms", address, sent, sucess, fail, loss * 100, minrtt, maxrtt, avgrtt);
                    _doIStop = false; _userRequestExit = false; sucess = 0; sent = 0; ttlrtt = 0; list.Clear(); fail = 0; loss = 0; avgrtt = 0; minrtt = 0; maxrtt = 0;
                }
                catch (Exception ee)
                {
                    Console.WriteLine("Ping request could not find host {0} ", website + ".Please check the name and try again.");
                    //Console.WriteLine(ee.ToString());
                }
            }
    		// Case ping -h
            private void help()
            {
                Console.WriteLine("\nUsage: ping [-t] [-a] [-n count] [-l size] [-f] [-i TTL] [-v TOS]\n            [-r count] [-s count] [[-j host-list] | [-k host-list]]\n            [-w timeout] [-R] [-S srcaddr] [-4] [-6] target_name\nOptions:\n     -t             Ping the specified host until stopped.\n                   To see statistics and continue - type Control-Break;\n                   To stop - type Control-C.\n    -a             Resolve addresses to hostnames.\n    -n count       Number of echo requests to send.\n    -l size        Send buffer size.\n    -f             Set Don't Fragment flag in packet (IPv4-only).\n    -i TTL         Time To Live.\n    -v TOS         Type Of Service (IPv4-only. This setting has been deprecated\n                   and has no effect on the type of service field in the IP Head\ner).\n    -r count       Record route for count hops (IPv4-only).\n    -s count       Timestamp for count hops (IPv4-only).\n    -j host-list   Loose source route along host-list (IPv4-only).\n    -k host-list   Strict source route along host-list (IPv4-only).\n    -w timeout     Timeout in milliseconds to wait for each reply.\n    -R             Use routing header to test reverse route also (IPv6-only).\n    -S srcaddr     Source address to use.\n    -4             Force using IPv4.\n    -6             Force using IPv6.");
            }
        }
    }

+ Reply to Thread

Tags for this Thread

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts