Пример #1
0
        public void InputHostData()//переименуй процедуру
        {
            //вывод данных из файла на экран, пронумерованным списком

            for (bool check = true; check == true;)
            {
                command = Console.ReadLine();
                switch (command)
                {
                //добавить редактирование данных по строке
                case "disp":
                    try
                    {
                        displayFileData();
                    }
                    catch (DirectoryNotFoundException)
                    {
                        Console.WriteLine("Файл отсутсвует");
                    }
                    break;

                case "start":
                    readFile();
                    check = false;
                    break;

                case "add":
                    enterByHand();    //ввод данных вручную
                    readFile();
                    check = false;
                    break;

                case "add -r":
                    enterByHand();    //ввод данных вручную
                    readFile();
                    check = false;
                    break;

                case "add -b":
                    enterByHand();    //ввод данных вручную
                    readFile();
                    check = false;
                    break;

                case "test":
                    Ping        pingSender = new Ping();
                    PingOptions options    = new PingOptions();

                    // Use the default Ttl value which is 128,
                    // but change the fragmentation behavior.
                    options.DontFragment = true;

                    // Create a buffer of 32 bytes of data to be transmitted.
                    string    data    = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
                    byte[]    buffer  = Encoding.ASCII.GetBytes(data);
                    int       timeout = 120;
                    PingReply reply   = pingSender.Send("10.10.10.10", timeout, buffer, options);
                    if (reply.Status == IPStatus.Success)
                    {
                        Console.WriteLine("Address: {0}", reply.Address.ToString());
                        Console.WriteLine("RoundTrip time: {0}", reply.RoundtripTime);
                        Console.WriteLine("Time to live: {0}", reply.Options.Ttl);
                        Console.WriteLine("Don't fragment: {0}", reply.Options.DontFragment);
                        Console.WriteLine("Buffer size: {0}", reply.Buffer.Length);
                    }
                    else
                    {
                        Console.WriteLine("Address: {0}", reply.Address.ToString());
                        Console.WriteLine("RoundTrip time: {0}", reply.RoundtripTime);
                        //Console.WriteLine("Time to live: {0}", reply.Options.Ttl);
                        // Console.WriteLine("Don't fragment: {0}", reply.Options.DontFragment);
                        Console.WriteLine("Buffer size: {0}", reply.Buffer.Length);
                    }
                    reply = pingSender.Send("8.8.8.8", timeout, buffer, options);
                    if (reply.Status == IPStatus.Success)
                    {
                        Console.WriteLine("Address: {0}", reply.Address.ToString());
                        Console.WriteLine("RoundTrip time: {0}", reply.RoundtripTime);
                        Console.WriteLine("Time to live: {0}", reply.Options.Ttl);
                        Console.WriteLine("Don't fragment: {0}", reply.Options.DontFragment);
                        Console.WriteLine("Buffer size: {0}", reply.Buffer.Length);
                    }
                    break;

                case "help":
                    Console.WriteLine("Наберите команду для продолжения");
                    Console.WriteLine("disp    - Вывести на экран содержимое файла \"HostDataBase.txt\"");
                    Console.WriteLine("start   - Запуск Пингера, по данным файла\"HostDataBase.txt\"");
                    Console.WriteLine("add     - для записи еще данных в конец файла, не стирая данные");
                    Console.WriteLine("add -r  - для удаления данных из файла и записи их в ручную через консоль");
                    Console.WriteLine("add -b  - будет сделан backup в \\%root_program_folder%\\Data\\backup\\%date%.txt");
                    break;

                default:
                    Console.WriteLine("Команда введена не верно, повторите ввод \n");
                    break;
                }
            }
        }
Пример #2
0
        public void CreateTableHost(List <Host> addressHost, int timeoutHost)
        {
            Ping        Pinger  = new Ping();
            PingOptions options = new PingOptions();

            options.DontFragment = true;
            String           HostName        = "";
            List <String>    tempHostName    = new List <String>();
            List <String>    tempIpAddress   = new List <String>();
            List <String>    tempDescription = new List <String>();
            List <int>       tempQualityHost = new List <int>();
            List <long>      tempRoadTrip    = new List <long>();
            outputDataPinger line            = new outputDataPinger();

            Console.Clear();
            Console.Write(" \n      Идет обработка доступности адресов, пожалуйста подождите...");
            for (long iterator = 1; ; iterator++)
            {
                if (NetworkInterface.GetIsNetworkAvailable())
                {
                    for (int i = 0; i < addressHost.Count; i++)
                    {
                        Host tempListHost = addressHost[i];
                        HostName = tempListHost.hostName;
                        try
                        {
                            PingReply ReplyInputDataHost = Pinger.Send(HostName, timeoutHost);
                            if (ReplyInputDataHost.Status != IPStatus.Success)
                            {
                                tempHostName.Add(HostName);
                                tempIpAddress.Add("not available");
                                tempRoadTrip.Add(ReplyInputDataHost.RoundtripTime);
                                tempDescription.Add(tempListHost.physLocationHost);
                                tempQualityHost.Add(tempListHost.Quality(false));
                            }
                            else
                            {
                                try
                                {
                                    tempHostName.Add(HostName);
                                    tempIpAddress.Add(ReplyInputDataHost.Address.ToString());
                                    tempRoadTrip.Add(ReplyInputDataHost.RoundtripTime);
                                    tempDescription.Add(tempListHost.physLocationHost);
                                    tempQualityHost.Add(tempListHost.Quality(true));
                                }
                                catch (NullReferenceException)
                                {
                                    tempHostName.Add(HostName);
                                    tempIpAddress.Add("not available");
                                    tempRoadTrip.Add(0);
                                    tempDescription.Add(tempListHost.physLocationHost);
                                    tempQualityHost.Add(tempListHost.Quality(false));
                                }
                            }
                        }
                        catch (PingException)
                        {
                            tempHostName.Add(HostName);
                            tempIpAddress.Add("HOST NAME ERROR!");
                            tempRoadTrip.Add(0);
                            tempDescription.Add(tempListHost.physLocationHost);
                            tempQualityHost.Add(tempListHost.Quality(false));
                        }
                        catch (ArgumentException)
                        {
                            tempHostName.Add(HostName);
                            tempIpAddress.Add("HOST NAME ERROR!");
                            tempRoadTrip.Add(0);
                            tempDescription.Add(tempListHost.physLocationHost);
                            tempQualityHost.Add(tempListHost.Quality(false));
                        }

                        /*//////////////////////////////////////////////////////////////////////
                         * ///  РАЗОБРАТЬСЯ С РАБОТОЙ ИСКЛЮЧЕНИЙ, что и когда перехватывают
                         *
                         * catch (ObjectDisposedException)
                         * {
                         * tempHostName.Add(HostName);
                         * tempIpAddress.Add("ObjectDisposedException!");
                         * tempRoadTrip.Add(999);
                         * tempDescription.Add(tempListHost.physLocationHost);
                         * tempQualityHost.Add(tempListHost.Quality(false));
                         * }
                         * catch (InvalidOperationException)
                         * {
                         * tempHostName.Add(HostName);
                         * tempIpAddress.Add("InvalidOperationException");
                         * tempRoadTrip.Add(999);
                         * tempDescription.Add(tempListHost.physLocationHost);
                         * tempQualityHost.Add(tempListHost.Quality(false));
                         * }
                         * //////////////////////////////////////////////////////////////////*/
                    }
                    Console.Clear();
                    line.writeHeadTable();
                    for (int i = 0; i < addressHost.Count; i++)
                    {
                        line.writeTextColor(tempHostName[i], tempIpAddress[i], tempRoadTrip[i], tempDescription[i], tempQualityHost[i]);
                        //Thread.Sleep(4);
                    }
                    tempHostName.Clear();
                    tempIpAddress.Clear();
                    tempRoadTrip.Clear();
                    tempDescription.Clear();
                    tempQualityHost.Clear();
                    //Thread.Sleep(250);
                    Console.ForegroundColor = ConsoleColor.White;
                }
                else
                {
                    Console.ForegroundColor = ConsoleColor.Gray;
                    Console.Clear();
                    Console.WriteLine(" \n \n \n \n \n \n             Связи нет! \n      ПРОВЕРЬТЕ СЕТЕВОЕ ПОДКЛЮЧЕНИЕ!pin");
                }
                Console.WriteLine("\nКоличество итераций = " + iterator);
                Thread.Sleep(1500);
            }
        }
Пример #3
0
        static void Main(string[] args)
        {
Start:
            Console.BackgroundColor = ConsoleColor.Black;
            Console.ForegroundColor = ConsoleColor.Green;
            Console.WriteLine("                                 ``.....```                                        ``.....``");
            Console.WriteLine("                            `.---.......---:-.`                             ``.-:--.......--:.`");
            Console.WriteLine("                          `-:.      `````   `-:/-.                       `.---.   `````      .-:.");
            Console.WriteLine("                         .:.          `.-/+syso//:-`                    `...:+sso+:.`          `:-`");
            Console.WriteLine("                       `-:`                  .+ymds:.                   .-//:.`                  --`");
            Console.WriteLine("                       .:`   `...``             `:oo:`                `-:-`              `````    --`");
            Console.WriteLine("                       ..-ohNNMMNNNmdyo/.          `-:.`            `--`          `:+ydmNmhs/:::-.`.`");
            Console.WriteLine("                        `.:ohdNNNNNMMMMMNms:`        `--           .-`         -odNMMMMMNms/.    ``");
            Console.WriteLine("                          `.:+yhdmddddNMMMMMNs-     /:::`          ...:`    .omMMMMMNmdddy+-`");
            Console.WriteLine("                            `.:+ydmNNNMMMMMMMMNd/   :y+-            `::   -yNMMMMMMMMMNNms/.");
            Console.WriteLine("                              `.+ymNNmddNMNMMMMMMd/  //.            .:  -hNMMMMMNMNddmmNmy/.");
            Console.WriteLine("                              .-::-:/+++hN+///oymMMh-`/-           `/``yNMNhs+///mmo++/:--:-`");
            Console.WriteLine("                            `-:`.ohyo/:-...-://:--omNo:+.`       `./+/mNy:-////--..-:/oshs:`--`    ```");
            Console.WriteLine("                     `...``-:.`+o-`            `.:`.dNmd-:`     `--ymNN- --`            `.+o``:-.`.-.-`");
            Console.WriteLine("                     .:/---.` +y-`              `.  oMMm./.     `:-hMMh  .`              `-oy  .---+o/.");
            Console.WriteLine("                    `-/+:.----`-/ooo+++/++/++++/:.:sNMMd +-.```../.oMMMh/.:/++++/++/++++oo+:``...`-/+:.");
            Console.WriteLine("                   `.:+smNNNNNms/-......+y..-:/ohmNMMMMo hyso+osyh.:MMMMNmy/-....oo........-://::::--..`");
            Console.WriteLine("                   ``:+yhhysssso+/:::::---.-:+ymNNMMMMN. NMNmhdNNN- dMMNdy+:-.....--:---..```      `..``");
            Console.WriteLine("                     `..--....```            .:+symNMM+  NMMmddMMM- -mmy+-`");
            Console.WriteLine("                                               `-/sdmo   NMMmddMMM:  -s/.");
            Console.WriteLine("                                                 `:o/   `MMMmddMMM/   .:.`");
            Console.WriteLine("                                                `.:.`/: .MMMmddMMM+ ./``:-`");
            Console.WriteLine("                                               `--`/dNs :MMMmddMMMs :Mm+..:.`");
            Console.WriteLine("                                         `.-.-//.:hNMM/ sMMNmmmNMMd .MMMm+.::-..-`");
            Console.WriteLine("                    `.`--```       ```.---.``od-sNMMMM- dMMNdddmMMN.`NMMMMh.ys. `---.```         `.-`.`");
            Console.WriteLine("                    `--`.:://////:::--...:+ymMM+NMMMMM: NMMMNmmNMMM:`NMMMMM+NMmh+:-..--------------`.:`");
            Console.WriteLine("                     .:`  -+-```-//+oshmmNMMMMMmmMMdhmh.+dNMMMMMNds.omdhNMNdMMMMMNNmdyo+//:```.//   :-");
            Console.WriteLine("                      -:  `hm-  .sNMMMMMMMMMMMMMMMMy/:oms//:///://ody::oMMMMMMMMMMMMMMMMMh-  .hm.  --`");
            Console.WriteLine("                      `--  .dN+   :dMMMMMMMMMMMMMMMMMNh+/syyyyysys+/yNNMMMMMMMMMMMMMMMMN+`  -mN:  -:`");
            Console.WriteLine("                       `:-  -mMs`  `oNMMMMMMMMMMMMMMNs.    `````    `+mMMMMMMMMMMMMMMMy.   +NN/  .:`");
            Console.WriteLine("                        `:-  -mMh.   -hMMMMMMMMMNNmy:      `oys.      .sdNNMMMMMMMMMd/   `sMN/  .:.");
            Console.WriteLine("                         `--  -dMm/   `-/////::--.`       :dMMMm+`      `..-:::////:`   -dMm/  -:`");
            Console.WriteLine("                          `-:` `oNNy-                   `sNMMMMMMh-                   `oNNy.  --`");
            Console.WriteLine("                           `.:`  :hNNy/::::::::::--....:hNNNNNmNNNd/....--::::::::::/smNd/  `:-`");
            Console.WriteLine("                             .:. `osymMMMMMMMMMMMMdo+/////::::::::////+ohNMMMMMMMMMMMmhss. .:.`");
            Console.WriteLine("                              `-:``ymhshdNMMMMMMMMMMMMNNNNNNNNNNNNNNNMMMMMMMMMMMMNmhyydd- --`");
            Console.WriteLine("                               `.:.`sNMmdhhdNMMMNdmNmmMMMMMMMMMMMMMMNmhhhyyyyyyssshmNMh.`:-`");
            Console.WriteLine("                                 `--`/mMMMMMNMMMmdmdddNNNNNNNNNNNNmdy+:::---....:+ydmo`--`");
            Console.WriteLine("                                   .:--hMMMMNNmdysoo+ooso:--------//-`           ./o:.:.`");
            Console.WriteLine("                                    `-:-sNMMNdyo:.``````-/.     `:-`            `.-.--`");
            Console.WriteLine("                                      `-:+dNNdo:`        -/     -:`             `.`.`");
            Console.WriteLine("                                       `.:/ydy+-        `:-     ./`               `");
            Console.WriteLine("                                         `.-/:-`        ./`      :-");
            Console.WriteLine("                                            ```         -:       -:");
            Console.WriteLine("                                                        -:       -:");
            Console.WriteLine("                                                        ./       ::");
            Console.WriteLine("                                                        ./`      /.");
            Console.WriteLine("                                                        `:-     ./`");
            Console.WriteLine("                                                         -/     --");
            Console.WriteLine("                                                         ./`    /.");
            Console.WriteLine("                                                          -:`  --`");
            Console.WriteLine("                                                           `...``");
            Console.WriteLine("      `...`     `....``    `..`      `..`     `..`     `....``      `....`   `.`    ..`   `..     `....`    `...`");
            Console.WriteLine("    `smmddd/  `sdmmmmmd+   mNNm/    -mNNm`    hNNm.    hNNddmdo   .ymmmmmmh: oNm-  /NN- -odMM-   :dmmNNd/  odddNNh`");
            Console.WriteLine("    /MM:` .. `dMh-  `/NMo  MMyMN.  `dMsMM`   oMhhMh    dMy  +MM. -NMs.  `oMM/ sMm.:NN:  so+MM-   .:``:MMd  -.  +MM/");
            Console.WriteLine("    `hNNhs:` /MM-     hMm  MM/sMh  yMs:MM`  -NN..NM+   dMmssmMs  sMN`     mMh  sMdNN:     -MM-       oMN/   osymNs`");
            Console.WriteLine("      -/yNMd`+MM-     hMm  MM:`mMo/Md`:MM` `dMh//hMN.  dMd//oNMs sMN`     NMy   yMM/      -MM-     -hMd:    //+yMNo");
            Console.WriteLine("    --```oMM..mMh.```+MN/  MM: -MMNN- :MM` sMmyyyymMd` dMy```dMd -NMs.``.sMN-   /MM`    ``:MM:`  .yMN+```  -```.NMm");
            Console.WriteLine("    +mmddNd:  .smNmdmmy:   NN:  oNN+  :NN`-NN-    -NN+ hNmddmms.  -yNNddNms.    /NN`    sdmNNmd+ yNNmmmmm:`dmddNNy-");
            Console.WriteLine("      ...`       `...      ``    ``    ``  ``      ```  ````         `..`        ``     ```````   ```````   `...   ");
            Console.WriteLine("");
            TcpClient tcpClient = new TcpClient();
            int       port      = 80;
            TcpClient client;

            Console.WriteLine("Pinger V1.0");
            Console.WriteLine("Made by: Somaboy123");
            Console.WriteLine("Enter IP or URL:");
            string    ip         = Console.ReadLine();
            Ping      ping       = new Ping();
            PingReply pingresult = ping.Send(ip);

            if (pingresult.Status.ToString() == "Success")
            {
                Console.WriteLine("Online");
            }
            else
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine("Offline");
                Console.ForegroundColor = ConsoleColor.Green;
            }
            Console.WriteLine("Want to use Pinger again? (y/n)");
            switch (Console.ReadLine())
            {
            case "y":
                Console.Clear();
                goto Start;

            case "n":
                break;
            }
        }
Пример #4
0
        static int Main(string[] args)
        {
            Ping        pingSender = new Ping();
            PingOptions options    = new PingOptions();
            // Create  the ping target object, aka pt
            PingerTarget pt      = new PingerTarget();
            bool         verbose = false;  // true = print additional versbose stuff for the program
            //bool loop = true; // true = ping will loop until Ctrl + C is pressed
            int    items             = -1; // compensate for "pinger" counting as 1 command line argument
            int    maxcount          = 0;
            bool   maxCountSpecified = false;
            bool   smartping         = true;                // by default use the smart ping switch
            bool   return_code_only  = false;
            string target            = "";                  // target IP address or DNS name to ping
            int    defaultPollingTimeInMilliseconds = 1000; //iteration defaultPollingTimeInMilliseconds in ms or can be seen as polling
            bool   stopBeeps         = false;
            bool   outputScreenToCSV = false;               // Output only what's on the screen to CSV. So if printing only changes then it will only output to file that
            bool   outputAllToCSV    = false;               // Output every ping response to CSV, even if you are using the smart ping function which only prints the status changes
            string outputCSVFilename = "";
            string outstr            = "";
            int    sleeptime         = defaultPollingTimeInMilliseconds;
            int    sleeptimesec      = sleeptime / 1000;
            double timelaps          = 0;
            int    runtimeError      = 0;
            int    runtimeInHours    = 0;

            // Create a buffer of 32 bytes of data to be transmitted.
            string data = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";

            byte[] buffer     = Encoding.ASCII.GetBytes(data);
            int    timeout    = 1000; // amount of time in ms to wait for the ping reply
            int    timeoutsec = timeout / 1000;

            // Use the default Ttl value which is 128,
            // but change the fragmentation behavior.

            // iterate through the arguments
            string[] arguments = Environment.GetCommandLineArgs();
            for (int argIndex = 0; argIndex < arguments.Length; argIndex++)
            {
                //logThis("Arguments " + arg);
                switch (arguments[argIndex].ToUpper())
                {
                case "/?":
                    ShowSyntax();
                    runtimeError = 1;
                    break;

                case "-R":     // Returns code only, doesn't expects a value after this switch
                    return_code_only  = true;
                    maxcount          = 1;
                    maxCountSpecified = true;
                    break;

                case "-V":
                    verbose = true;
                    break;

                case "-S":     // Make pinger like ping and output every responses to screen
                    smartping = false;
                    break;

                case "-N":     // No loop, same as using '-c 1'
                    maxcount          = 1;
                    maxCountSpecified = true;
                    //loop = false;
                    break;

                case "-Q":     // quietens audible sounds (beeps)
                    stopBeeps = true;
                    break;

                case "-C":     // Specify how many times pinger will loop ping a host, expects a positive value after the switch equal or greater than 1
                    try
                    {
                        argIndex++;     // get the next value, hopefully a digit
                        //bool success = int.TryParse(arguments[argIndex], out sleeptime);
                        maxCountSpecified = true;
                        maxcount          = int.Parse(arguments[argIndex]);
                    }
                    catch (System.ArgumentNullException)
                    {
                        logThis("Please specify a valid number.");
                        runtimeError = 1;
                    }
                    catch (System.FormatException)
                    {
                        logThis("Please specify a valid number.");
                        runtimeError = 1;
                    }
                    catch (System.OverflowException)
                    {
                        logThis("Please specify a valid number.");
                        runtimeError = 1;
                    }
                    catch (System.IndexOutOfRangeException)
                    {
                        logThis("Please specify a valid number.");
                        runtimeError = 1;
                    }
                    break;

                case "-H":     // Run pinger for a number of hours, expects a positive value after the switch
                    try
                    {
                        argIndex++;     // get the next value, hopefully a digit
                        //bool success = int.TryParse(arguments[argIndex], out sleeptime);
                        runtimeInHours    = int.Parse(arguments[argIndex]);
                        maxCountSpecified = false;
                        //loop = true;
                    }
                    catch (System.ArgumentNullException)
                    {
                        logThis("Please specify a valid number.");
                        runtimeError = 1;
                    }
                    catch (System.FormatException)
                    {
                        logThis("Please specify a valid number.");
                        runtimeError = 1;
                    }
                    catch (System.OverflowException)
                    {
                        logThis("Please specify a valid number.");
                        runtimeError = 1;
                    }
                    catch (System.IndexOutOfRangeException)
                    {
                        logThis("Please specify a valid number.");
                        runtimeError = 1;
                    }
                    break;

                case "-CSV":     // Output each ping responses to a CSV file but matches onscreen output.
                    //verbose = false;
                    outputScreenToCSV = true;
                    outputAllToCSV    = !outputScreenToCSV;
                    break;

                case "-CSVALL":     // Output each ping responses to a CSV file even if you are using the smartping function
                    //verbose = false;
                    outputScreenToCSV = false;
                    outputAllToCSV    = !outputScreenToCSV;
                    break;

                case "-P":     // Poll every 'n' seconds, expects a value after this switch
                    try
                    {
                        argIndex++;     // get the next value, hopefully a digit
                        //bool success = int.TryParse(arguments[argIndex], out sleeptime);
                        sleeptime = int.Parse(arguments[argIndex]) * 1000;
                    }
                    catch (System.ArgumentNullException)
                    {
                        logThis("Please specify a valid polling interval in seconds.");
                        runtimeError = 1;
                    }
                    catch (System.FormatException)
                    {
                        logThis("Please specify a valid polling interval in seconds.");
                        runtimeError = 1;
                    }
                    catch (System.OverflowException)
                    {
                        logThis("Please specify a valid polling interval in seconds.");
                        runtimeError = 1;
                    }
                    catch (System.IndexOutOfRangeException)
                    {
                        logThis("Please specify a valid polling interval in seconds.");
                        runtimeError = 1;
                    }
                    break;

                case "-T":     // smart switch
                    // Show OK and Down and OK, implies -C
                    try
                    {
                        argIndex++;     // get the next value, hopefully a digit
                        timeout = int.Parse(arguments[argIndex]) * 1000;
                    }
                    catch (System.ArgumentNullException)
                    {
                        logThis("Please specify a valid timeout value in seconds larger than 1 seconds.");
                        runtimeError = 1;
                    }
                    catch (System.FormatException)
                    {
                        logThis("Please specify a valid timeout value in seconds larger than 1 seconds.");
                        runtimeError = 1;
                    }
                    catch (System.OverflowException)
                    {
                        logThis("Please specify a valid timeout value in seconds larger than 1 seconds.");
                        runtimeError = 1;
                    }
                    catch (System.IndexOutOfRangeException)
                    {
                        logThis("Please specify a valid timeout value in seconds larger than 1 seconds.");
                        runtimeError = 1;
                    }
                    break;

                default:
                    if (items == 0)
                    {
                        target = arguments[argIndex];
                        //smartping = true;
                    }
                    items++;
                    break;
                }
            }

            if (runtimeError > 0)
            {
                return(runtimeError);
            }

            if (items > 1 || target.Length <= 0)
            {
                ShowSyntax();
                runtimeError = 1;
            }
            else
            {
                pt.Target    = target;
                pt.Startdate = DateTime.Now;

                string[] dnsresults = DNSLookup(pt.Target);

                if (dnsresults.Length > 0)
                {
                    pt.Hostname        = dnsresults[0];
                    pt.IPAddress       = dnsresults[1];
                    pt.DNSLookupStatus = dnsresults[2];
                }
                else
                {
                    pt.Hostname = pt.Target;
                }


                if (!return_code_only)
                {
                    logThis("Pinging " + pt.Target + " at " + sleeptimesec + "sec interval & timeout of " + timeoutsec + " seconds");
                    logThis("Looking up DNS : ");
                    logThis("      Hostname : " + pt.Hostname);
                    logThis("      IPAddress: " + pt.IPAddress);
                    logThis("");
                    if (!maxCountSpecified && runtimeInHours > 0)
                    {
                        maxcount = (runtimeInHours * 60 * 60) / (sleeptimesec);
                        //logThis(">> sleeptime = " + sleeptimesec + ",runtimeInHours=" + runtimeInHours + "hrs,maxcount=" + maxcount +"<<");
                        logThis(">> Runtime: " + runtimeInHours + "hrs, Total ping expected=" + maxcount + " <<");
                    }
                }
                if (outputScreenToCSV || outputAllToCSV)
                {
                    outputCSVFilename = "pinger-" + pt.Target.Replace('.', '_').Trim() + "_" + ".txt";
                    logThis(">> Responses will be saved to " + outputCSVFilename);
                    logThis("");
                    logToFile("Date,TimeLaps (sec),Target,Reply,Round Trip (ms),TTL,Count", outputCSVFilename);
                }
                if (!return_code_only)
                {
                    logThis("Date,TimeLaps (sec),Target,Reply,Round Trip (ms),TTL,Count");
                }
                do
                {
                    pt.CurrStatusPingDate = DateTime.Now;
                    pt.CurrHostPingCount++;
                    try
                    {
                        options.DontFragment = true;
                        PingReply reply;

                        if (pt.IPAddress != null)
                        {
                            reply = pingSender.Send(pt.IPAddress, timeout, buffer, options);
                            //pt.CurrHostPingCount++; // redundant with the one below ? should I take it outside this if else..may..no time to test it thought.
                        }
                        else
                        {
                            reply = pingSender.Send(pt.Hostname, timeout, buffer, options);
                            //pt.CurrHostPingCount++; // redundant with the one one ? should I take it outside this if else..may..no time to test it thought.
                        }

                        if (reply != null && reply.Options != null)
                        {
                            pt.OptionsTtl = reply.Options.Ttl;
                        }
                        else
                        {
                            pt.OptionsTtl = -1;
                        }

                        pt.ReplyIPAddress     = reply.Address.ToString(); // ? reply.Address.ToString() : "-";
                        pt.RoundTrip          = reply.RoundtripTime;      //? reply.RoundtripTime : -1);
                        pt.CurrHostPingStatus = reply.Status.ToString();  //? reply.Status.ToString() : "-");
                        // logThis(reply.Status.ToString());
                        if (reply.Status.ToString() == "DestinationHostUnreachable")
                        {
                            pt.Errorcode          = 1;
                            pt.CurrHostPingStatus = "DestinationHostUnreachable";
                        }
                        else
                        {
                            pt.Errorcode = 0;
                        }
                    }
                    catch (System.Net.Sockets.SocketException se)
                    {
                        pt.Errorcode = 1; pt.ErrorMsg = se.Message; pt.CurrHostPingStatus = se.Message; Thread.Sleep(sleeptime);
                    }
                    catch (System.Net.NetworkInformation.PingException pe)
                    {
                        pt.Errorcode = 1; pt.ErrorMsg = pe.Message; pt.CurrHostPingStatus = pe.Message; Thread.Sleep(sleeptime);
                    }
                    catch (System.NullReferenceException nre)
                    {
                        pt.Errorcode = 1; pt.ErrorMsg = nre.Message; pt.CurrHostPingStatus = "DestinationHostUnreachable"; Thread.Sleep(sleeptime);
                        //pt.Errorcode = 1; pt.ErrorMsg = nre.Message; pt.CurrHostPingStatus = nre.Message; Thread.Sleep(sleeptime);
                    }
                    finally
                    {
                        if (pt.Errorcode == 0)
                        {
                            pt.HostReachableCountUpdate++;
                            // timelaps = (sleeptimesec) * (pt.CurrHostPingCount - pt.PrevStatusPingCount);
                        }
                        else if (pt.Errorcode == 1)
                        {
                            pt.HostUnreachableCountUpdate++;
                            // timelaps = (sleeptimesec) * (pt.CurrHostPingCount - pt.PrevStatusPingCount);timelaps = (sleeptimesec + timeoutsec) * (pt.CurrHostPingCount - pt.PrevStatusPingCount);
                        }
                        else
                        {
                            logThis("Unknown ping error code");
                        }

                        TimeSpan difference = pt.CurrStatusPingDate.Subtract(pt.PrevStatusPingDate);
                        timelaps = Math.Ceiling(difference.TotalSeconds);
                        // Create the output string
                        if (!verbose)
                        {
                            outstr = pt.CurrStatusPingDate + "," + timelaps + "sec," + pt.Hostname + "," + pt.CurrHostPingStatus + "," + pt.RoundTrip + "ms," + pt.OptionsTtl + "," + pt.CurrHostPingCount;
                        }
                        else
                        {
                            outstr = "Date=" + pt.CurrStatusPingDate + ",TimeLapsSec=" + timelaps + "sec,trgt=" + pt.Hostname + ",status=" + pt.CurrHostPingStatus + ",rndtrip=" + pt.RoundTrip + "ms,ttl=" + pt.OptionsTtl + ",count=" + pt.CurrHostPingCount;
                        }

                        if (pt.PrevHostPingStatus != pt.CurrHostPingStatus)
                        {
                            pt.PrevStatusPingDate = pt.CurrStatusPingDate;
                            // 1 print to screent the difference
                            if (!return_code_only)
                            {
                                logThis(outstr);
                            }
                            // 2 - write to log file if requested to
                            if (outputScreenToCSV || outputAllToCSV)
                            {
                                logToFile(outstr, outputCSVFilename);
                            }

                            if (pt.Errorcode == 0 && pt.CurrHostPingCount > 1 && !stopBeeps)
                            {
                                for (int i = 0; i < 2; i++)
                                {
                                    Console.Beep();
                                }
                            }
                            else if (pt.Errorcode == 1 && pt.CurrHostPingCount > 1 && !stopBeeps) //&& smartping
                            {
                                for (int i = 0; i < 4; i++)
                                {
                                    Console.Beep();
                                }
                            }
                            pt.PrevStatusPingCount = pt.CurrHostPingCount;
                        }
                        else // At this point the current and previous ping status differ so we need to process
                        {
                            // Only output to screen if the smart ping is not enabled and pinger behaves like ping
                            if (!smartping)
                            {
                                if (!return_code_only)
                                {
                                    logThis(outstr);
                                }
                            }
                            // Only output to screen if the
                            if (outputAllToCSV)
                            {
                                logToFile(outstr, outputCSVFilename);
                            }
                        }
                    }
                    if (!maxCountSpecified)
                    {
                        maxcount = pt.CurrHostPingCount + 1;
                    }
                    if (verbose)
                    {
                        pt.Printout();
                    }
                    //if (loop) { Thread.Sleep(sleeptime); }
                    if (pt.CurrHostPingCount < maxcount)
                    {
                        Thread.Sleep(sleeptime);
                    }
                } while (pt.CurrHostPingCount < maxcount);
                //while (loop && pt.CurrHostPingCount < maxcount) ;
            }
            //logThis(pt.Errorcode.ToString());
            return(pt.Errorcode);
        }
Пример #5
0
        private void Sendicmp(IPAddress addresstoping)
        {
            status   = IPStatus.Unknown;
            rtt      = 0;
            bitesize = 0;
            ttl      = 0;
            seq      = 0;
            PingReply reply       = null;
            var       tokenSource = new CancellationTokenSource();
            var       token       = tokenSource.Token;

            try
            {
                int x = 0;
                senttotal++;
                try
                {
                    reply = pingSender.Send(addresstoping, 2000, icmpdata);
                }
                catch (System.ArgumentNullException)
                {
                    MessageBox.Show("Could not resolve hostname2");
                }
                Thread.Sleep(1);
                while (x < 50)
                {
                    if (reply.Buffer.Length == 0)
                    {
                        if (cancelrequested == true)
                        {
                            break;
                        }
                        Thread.Sleep(50);
                        x++;
                        continue;
                    }
                    break;
                }
                //Task updatetask = Task.Factory.StartNew(() => reply = pingSender.Send(addresstoping, 5000, icmpdata));
                //updatetask.Wait();
            }
            catch (PingException e)
            {
                //MessageBox.Show("Exception thrown while sending ping: Something went wrong at the system level, likely a physical malfunction. Exception thrown was: \n" + Convert.ToString(e));
                status = IPStatus.Unknown;
            }
            catch (Win32Exception e)
            {
                status = IPStatus.Unknown;
                //MessageBox.Show("Exception thrown while sending ping: Something went wrong at the system level, likely a physical malfunction. Exception thrown was: \n" + Convert.ToString(e));
            }
            if (reply != null)
            {
                status   = reply.Status;
                rtt      = reply.RoundtripTime;
                bitesize = reply.Buffer.Length;
            }
            else
            {
                status   = IPStatus.Unknown;
                rtt      = 0;
                bitesize = 0;
            }
            try
            {
                ttl = (reply.Options.Ttl);
            }
            catch (NullReferenceException e)
            {
                //MessageBox.Show("Null ref exception while setting ttl " + Convert.ToString(e));
                ttl = 0;
            }
            if (status == IPStatus.Success)
            {
                rtts.Add(Convert.ToInt16(reply.RoundtripTime));
                receivedtotal++;
            }
            else
            {
                losttotal++;
                return;
            }
            //MessageBox.Show("Status after ping " + Convert.ToString(status));
            return;
        }