Exemple #1
0
        public void ReadAndPing(string path)
        {
            File.OpenRead(path);
            ConsoleKeyInfo btn;

               do // Начала цикла
               {
                string ip = File.ReadLines(path);
                while (true) //читаем в ip строки из файла в path
                {
                    //Console.WriteLine(ip);
                    Ping pingSender = new Ping();
                    PingOptions options = new PingOptions();

                    options.Ttl = 60; //Продолжительность жизни пакета в секундах
                    int timeout = 120; //Таймаут выводется в ответе reply.RoundtripTime
                    string data = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"; //Строка длиной 32 байта
                    byte[] buffer = Encoding.ASCII.GetBytes(data); //Преобразование строки в байты, выводится reply.Buffer.Length

                    PingReply reply = pingSender.Send(ip, timeout, buffer, options);

                    Console.WriteLine("Сервер: {0} Время={1} TTL={2}", reply.Address.ToString(), reply.RoundtripTime, reply.Options.Ttl); //Выводим всё на консоль

                    //ConsoleKeyInfo btn = Console.ReadKey(); //Создаём переменную которая хранит метод Описывающий нажатую клавишу консоли
                    //if (btn.Key == ConsoleKey.Escape) break;

                }

                //  ConsoleKeyInfo btn = Console.ReadKey(); //Создаём переменную которая хранит метод Описывающий нажатую клавишу консоли
                //  if (btn.Key == ConsoleKey.Escape) break;
            btn = Console.ReadKey(); //Переенная для чтения нажатия клавиши
            }
            while (btn.Key == ConsoleKey.Escape); //Чтение нажатия клавиши.
        }
        public static bool checkInternetConnection()
        {
            Ping myPing = new Ping();
            String host = "google.com";
            byte[] buffer = new byte[5];
            int timeout = 50;
            PingOptions pingOptions = new PingOptions();
            try
            {
                PingReply reply = myPing.Send(host, timeout, buffer, pingOptions);
                if (reply.Status == IPStatus.Success)
                {
                    return true;
                }
            }
            catch (PingException exp)
            {
                Logs.system("Intenet connection not available: " + exp.Message, Logs.TYPE_ERROR, exp);
                return false;
            }
            catch (Exception exp)
            {
                Logs.system("Internet connection not available: " + exp.Message, Logs.TYPE_ERROR, exp);
                return false;
            }

            return false;
        }
Exemple #3
0
        public static PingResult PingHost(string host, int timeout = 1000, int pingCount = 4, int waitTime = 100)
        {
            PingResult pingResult = new PingResult();
            IPAddress address = GetIpFromHost(host);
            byte[] buffer = new byte[32];
            PingOptions pingOptions = new PingOptions(128, true);

            using (Ping ping = new Ping())
            {
                for (int i = 0; i < pingCount; i++)
                {
                    try
                    {
                        PingReply pingReply = ping.Send(address, timeout, buffer, pingOptions);

                        if (pingReply != null)
                        {
                            pingResult.PingReplyList.Add(pingReply);
                        }
                    }
                    catch (Exception e)
                    {
                        DebugHelper.WriteException(e);
                    }

                    if (waitTime > 0 && i + 1 < pingCount)
                    {
                        Thread.Sleep(waitTime);
                    }
                }
            }

            return pingResult;
        }
Exemple #4
0
 public static int Main(string[] args)
 {
     try {
         Arguments CommandLine=new Arguments(args);
         if (CommandLine["ip"]!=null) {
             string pingIP = CommandLine["ip"];
             Ping pingSender = new Ping();
             PingOptions options = new PingOptions();
             options.DontFragment=true;
             string data = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
             byte[] buffer = Encoding.ASCII.GetBytes(data);
             int timeout = 120;
             PingReply reply = pingSender.Send(pingIP,timeout,buffer,options);
             if (reply.Status==IPStatus.Success) {
                 WriteToConsole("RoundTrip time: "+reply.RoundtripTime);
             } else if (reply.Status==IPStatus.TimedOut) {
                 return (int) ExitCode.Timeout;
             }
         } else {
             printHelp();
         }
         return (int) ExitCode.Success;
     } catch (Exception) {
         return (int) ExitCode.Error;
     }
 }
 private void buttonPing_Click(object sender, EventArgs e)
 {
     this.listBoxResult.Items.Clear();
     //远程服务器IP
     string ipString = this.textBoxRemoteIp.Text.ToString().Trim();
     //构造Ping实例
     Ping pingSender = new Ping();
     //Ping选项设置
     PingOptions options = new PingOptions();
     options.DontFragment = true;
     //测试数据
     string data = "test data abcabc";
     byte[] buffer = Encoding.ASCII.GetBytes(data);
     //设置超时时间
     int timeout = 120;
     //调用同步send方法发送数据,将返回结果保存至PingReply实例
     PingReply reply = pingSender.Send(ipString, timeout, buffer, options);
     if (reply.Status == IPStatus.Success)
     {
         listBoxResult.Items.Add("答复的主机地址: " + reply.Address.ToString());
         listBoxResult.Items.Add("往返时间: " + reply.RoundtripTime);
         listBoxResult.Items.Add("生存时间(TTL): " + reply.Options.Ttl);
         listBoxResult.Items.Add("是否控制数据包的分段: " + reply.Options.DontFragment);
         listBoxResult.Items.Add("缓冲区大小: " + reply.Buffer.Length);
     }
     else
     {
         listBoxResult.Items.Add(reply.Status.ToString());
     }
 }
Exemple #6
0
        public static void isValidDomain()
        {
            try
            {
                Ping pingsender = new Ping();
                PingOptions options = new PingOptions(128, true);
                string data = "aaaaaaaaaaaaaaaaaaa";
                byte[] buffer = Encoding.ASCII.GetBytes(data);
                /*PingReply reply = pingsender.Send(Classes.variablen.domain);

                if (reply.Status == IPStatus.Success)
                {
                    Console.ForegroundColor = ConsoleColor.Green;
                    Console.WriteLine("Domain wurde gefunden!");
                    Console.ForegroundColor = ConsoleColor.Gray;
                }
                else if (reply.Status == IPStatus.TimedOut)
                {
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.WriteLine("Domain wurde nicht gefunden!");
                    Console.ForegroundColor = ConsoleColor.Gray;
                }*/
            }
            catch (Exception ex)
            {
                Classes.logger._elogger(ex);
            }
        }
        bool Ping(string host)
        {
            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 = 500;
            PingReply reply = pingSender.Send(host, timeout, buffer, options);
            if (reply.Status == IPStatus.Success)
            {
                Console.WriteLine("Ping successful, getting HTTP response code");
                return true;
            }
            else
            {
                Console.WriteLine("Ping Failed, server is either down or took too long to respond.");
                return false;
            }
        }
 public static bool isAlive(string IP)
 {
     try
     {
         Ping pingSender = new Ping();
         PingOptions options = new PingOptions();
         options.DontFragment = true;
         string data = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
         byte[] buffer = Encoding.ASCII.GetBytes(data);
         int timeout = 10;
         PingReply reply = pingSender.Send(IP, timeout, buffer, options);
         if (reply.Status == IPStatus.Success)
         {
             return (true);
         }
         else
         {
             Settings.SetLog("Failed to ping " + IP);
             return (false);
         }
     }
     catch (Exception e)
     {
         Settings.SetLog("Failed to ping " + IP);
         return (false);
     }
 }
        /// <summary>
        /// Permet de tester la bonne connectivité avec une adresse IP.
        /// </summary>
        /// <param name="IP"></param>
        /// <returns></returns>
        public static Boolean CheckConnectionIpInformations(string IP)
        {
            if (!String.IsNullOrEmpty(IP))
            {
                using (Ping pingSender = new Ping())
                {
                    PingOptions options = new PingOptions();
                    options.DontFragment = true;

                    String data = new String('a', 32);
                    byte[] buffer = Encoding.ASCII.GetBytes(data);
                    int timeout = 20;
                    try
                    {
                        PingReply reply = pingSender.Send(IP, timeout, buffer, options);
                        if (reply.Status != IPStatus.Success)
                        {
                            Notifier.ShowMessage("Adresse IP du serveur MySQL (ou MariaDB) est injoignable.", "Serveur MySQL injoignable", "error", 3);
                            return false;
                        }
                    }
                    catch
                    {
                        Notifier.ShowMessage("Impossible d'établir un test sur l'adresse IP du serveur MySQL (ou MariaDB).", "Adresse IP non testable", "error", 3);
                        return false;
                    }
                    return true;
                }
            }
            else
            {
                Notifier.ShowMessage("Adresse IP serveur MySQL (ou MariaDB) incorrecte.", "Format de l'adresse IP", "error", 3);
                return false;
            }
        }
 public static async Task<PingReply> Ping(string hostNameOrIPAddress, int ttl = 0)
 {
     var pinger = new Ping();
     var options = new PingOptions(ttl, dontFragment: true);
     
     return await pinger.SendTaskAsync(hostNameOrIPAddress, 0x1388, DefaultSendBuffer, options);
 }
Exemple #11
0
        public Ping()
        {
            this.InitializeComponent();
            this.DoUpdateForm = this.UpdateForm;

            // Create a buffer of 32 bytes of data to be transmitted.
            this.buffer = Encoding.ASCII.GetBytes(new String('.', 32));
            // Jump though 50 routing nodes tops, and don't fragment the packet
            this.packetOptions = new PingOptions(50, true);

            this.InitializeGraph();

            this.dataGridView1.SuspendLayout();

            this.dataGridView1.Columns.Add("1", "Count");
            this.dataGridView1.Columns.Add("2", "Status");
            this.dataGridView1.Columns.Add("3", "Host name");
            this.dataGridView1.Columns.Add("4", "Destination");
            this.dataGridView1.Columns.Add("5", "Bytes");
            this.dataGridView1.Columns.Add("6", "Time to live");
            this.dataGridView1.Columns.Add("7", "Roundtrip time");
            this.dataGridView1.Columns.Add("8", "Time");

            this.dataGridView1.ResumeLayout(true);
        }
Exemple #12
0
 private void frm_wait_Shown(object sender, EventArgs e)
 {
     frm_main frm = (frm_main)this.Owner;
     address = frm.current_pos;
     curr_pos = address;
     //Ping POS
     Ping png = new Ping();
     PingOptions opt = new PingOptions();
     opt.DontFragment = true;
     string data = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
     byte[] buffer = Encoding.ASCII.GetBytes (data);
     int timeout = 800;
     PingReply reply = png.Send(address, timeout, buffer, opt);
     if (reply.Status == IPStatus.Success)
     {
         if (Directory.Exists(@"\\" + address + @"\POS\Command\"))
         {
             address = @"\\" + address + @"\POS\Command\req18";
             using (File.Create(address)) { }
         }
         else
         {
             MessageBox.Show("Нету связи с POS терминалом или папка Command не доступна", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
             this.Close();
         }
     }
     else
     {
         MessageBox.Show("Нету связи с POS терминалом или папка Command не доступна", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
         this.Close();
     }
     bg_worker.WorkerSupportsCancellation = true;
     bg_worker.RunWorkerAsync();
 }
Exemple #13
0
        static void PingServer()
        {
            using (StreamReader reader = new StreamReader("guiConfig.json"))
            {
                string serverJson = reader.ReadToEnd();
                ServerModel serverModel = JsonConvert.DeserializeObject<ServerModel>(serverJson);

                if (serverModel != null && serverModel.configs != null && serverModel.configs.Count > 0)
                {
                    foreach (Server server in serverModel.configs)
                    {
                        string strIp = server.server;
                        Ping ping = new Ping();
                        PingOptions options = new PingOptions();
                        options.DontFragment = true;
                        //测试数据
                        string data = "test data abcabc";
                        byte[] buffer = Encoding.ASCII.GetBytes(data);
                        //设置超时时间
                        int timeout = 2000;
                        //调用同步 send 方法发送数据,将返回结果保存至PingReply实例
                        PingReply reply = ping.Send(strIp, timeout, buffer, options);
                        if (reply.Status == IPStatus.Success)
                        {
                            Console.WriteLine(string.Format("{0}---delay: {1}ms", server.remarks, reply.RoundtripTime));
                        }
                    }
                }
            }
        }
        private void PingServer(string server)
        {
            string result = "Test failed!";

            var pingSender = new Ping();
            var options = new PingOptions();
            options.DontFragment = true;

            // Create a buffer of 32 bytes of data to be transmitted.
            const string data = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
            byte[] buffer = Encoding.ASCII.GetBytes(data);
            const int timeout = 120;
            try
            {
                var reply = pingSender.Send(server, timeout, buffer, options);
                if (reply != null && reply.Status == IPStatus.Success)
                {
                    result = String.Format("Address: {0}\n", reply.Address.ToString());
                    result += String.Format("RoundTrip time: {0}\n", reply.RoundtripTime);
                    result += String.Format("Buffer size: {0}\n", reply.Buffer.Length);
                    result += Environment.NewLine;
                    result += "Test successful!\n";
                }
            }
            catch (Exception) { }

            MessageBox.Show(result, "Test Result");
        }
Exemple #15
0
 public PingReply Ping(string hostOrIp)
 {
     Ping pingSender = new Ping();
     //Ping 选项设置
     PingOptions options = new PingOptions();
     options.DontFragment = true;
     //测试数据
     string data = "test data abcabc";
     byte[] buffer = Encoding.ASCII.GetBytes(data);
     //设置超时时间
     int timeout = 1200;
     //调用同步 send 方法发送数据,将返回结果保存至PingReply实例
     var reply = pingSender.Send(hostOrIp, timeout, buffer, options);
     if (reply.Status == IPStatus.Success)
     {
         return reply;
         /*lst_PingResult.Items.Add("答复的主机地址:" + reply.Address.ToString());
         lst_PingResult.Items.Add("往返时间:" + reply.RoundtripTime);
         lst_PingResult.Items.Add("生存时间(TTL):" + reply.Options.Ttl);
         lst_PingResult.Items.Add("是否控制数据包的分段:" + reply.Options.DontFragment);
         lst_PingResult.Items.Add("缓冲区大小:" + reply.Buffer.Length);  */
     }
     else
         throw new ApplicationException("Can't find the arrive at target " + hostOrIp.ToString());
 }
Exemple #16
0
        private async void InternalSendAsync(IPAddress address, byte[] buffer, int timeout, PingOptions options)
        {
            AsyncOperation asyncOp = _asyncOp;
            SendOrPostCallback callback = _onPingCompletedDelegate;

            PingReply pr = null;
            Exception pingException = null;

            try
            {
                if (RawSocketPermissions.CanUseRawSockets())
                {
                    pr = await SendIcmpEchoRequestOverRawSocket(address, buffer, timeout, options).ConfigureAwait(false);
                }
                else
                {
                    pr = await SendWithPingUtility(address, buffer, timeout, options).ConfigureAwait(false);
                }
            }
            catch (Exception e)
            {
                pingException = e;
            }

            // At this point, either PR has a real PingReply in it, or pingException has an Exception in it.
            var ea = new PingCompletedEventArgs(
                pr,
                pingException,
                false,
                asyncOp.UserSuppliedState);

            Finish();
            asyncOp.PostOperationCompleted(callback, ea);
        }
Exemple #17
0
        /* Ping an entered address */
        public void PingAddress(string addr)
        {
            List<IPStatus> replies = new List<IPStatus>();

            int count = 0;

            // send 4 pings
            while (count < 4)
            {
                // used to construct a 32 byte message
                string data = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
                byte[] buffer = Encoding.ASCII.GetBytes(data);
                int timeout = 120;

                // intalize the ping object with ttl and no fragment options
                PingOptions PingSettings = new PingOptions(53, true);
                Ping Pinger = new Ping();

                // send the ping
                PingReply Reply = Pinger.Send(addr, timeout, buffer, PingSettings);

                replies.Add(Reply.Status);

                ++count;
            }

            // tracks the ammount of successful replies
            for (int i = 0; i < replies.Count; i++)
                if (replies[i] == IPStatus.Success)
                    scount++;
        }
Exemple #18
0
        public static bool PingIpOrDomainName(string strIpOrDname) {

            try
            {
                Ping objPingSender = new Ping();
                PingOptions objPinOptions = new PingOptions();
                objPinOptions.DontFragment = true;
                string data = "";
                byte[] buffer = Encoding.UTF8.GetBytes(data);
                int intTimeout = 120;
                PingReply objRPinReply = objPingSender.Send(strIpOrDname, intTimeout, buffer, objPinOptions);
                string strInfo = objRPinReply.Status.ToString();
                if (strInfo == "Success")
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
            catch (Exception)
            {
                return false;
            }
        }
Exemple #19
0
        public void launchPing(string IPAddress, string Hostname)
        {
            Ping newPing = new Ping();
            PingOptions options = new PingOptions();
            string data = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
            byte[] buffer = Encoding.ASCII.GetBytes(data);
            int timeout = 120;
            bool shouldLoop = true;

            while (shouldLoop == true)
            {
                PingReply reply = newPing.Send(IPAddress, timeout, buffer, options);

                if (reply.Status == IPStatus.Success)
                {
                    Console.Title = Hostname;
                    Console.WriteLine("Reply from Address: {0} with a round trip time of {1}ms", IPAddress, reply.RoundtripTime.ToString());
                    System.Threading.Thread.Sleep(1000);
                }
                else
                {
                    Console.WriteLine("Destination host unreachable or is not responding.");
                    System.Threading.Thread.Sleep(1000);
                }
            }
        }
Exemple #20
0
        public static string[] ping(string host)
        {
            try
            {
                Ping pingSender = new Ping();
                PingOptions options = new PingOptions();

                // Use the default Ttl value which is 128, e
                // 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(host, timeout, buffer, options);
                string[] ping = new string[2];
                if (reply.Status == IPStatus.Success)
                {

                    ping[0] = reply.RoundtripTime.ToString();
                    ping[1] = reply.Options.Ttl.ToString();

                }
                else { ping[0] = "Error"; }

                return ping;
            }
            catch
            {
                string[] err = new string[1];
                err[0] = "Error\n Possibly you entered a malformed IP or domain.";
                return err;
            }
        }
Exemple #21
0
 public static void Trace(IPAddress destination, Func<IPAddress, TracertNode, bool> callback)
 {
     if (destination == null)
     {
         throw new ArgumentNullException("destination");
     }
     else
     {
         if (callback == null)
         {
             throw new ArgumentNullException("callback");
         }
         else
         {
             var syncroot = new object();
             var buffer = new byte[INT_BufferSize];
             var options = new PingOptions(1, true);
             var ping = new Ping();
             ping.PingCompleted += (sender, e) =>
             {
                 var address = e.Reply.Address;
                 var status = e.Reply.Status;
                 back:
                 var done = !callback.Invoke(destination, new TracertNode(address, status, e.Reply.Options.Ttl)) || address.Equals(destination);
                 if (done)
                 {
                     try
                     {
                         if (ping != null)
                         {
                             ping.Dispose();
                         }
                     }
                     finally
                     {
                         ping = null;
                     }
                 }
                 else
                 {
                     lock (syncroot)
                     {
                         if (ping == null)
                         {
                             address = destination;
                             status = IPStatus.Unknown;
                             goto back;
                         }
                         else
                         {
                             options.Ttl++;
                             ping.SendAsync(destination, INT_TimeoutMilliseconds, buffer, options, null);
                         }
                     }
                 }
             };
             ping.SendAsync(destination, INT_TimeoutMilliseconds, buffer, options, null);
         }
     }
 }
Exemple #22
0
        /// <summary>
        /// Ping network address
        /// </summary>
        /// <param name="address">IP Address or Hostname</param>
        /// <returns></returns>
        public static bool SendPing(string address, int tries)
        {
            int tries_count = 0;
            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;
            while (tries_count < tries)
            {
                PingReply reply = pingSender.Send(address, timeout, buffer, options);
                if (reply.Status == IPStatus.Success)
                    return true;

                tries_count++;
            }

            return false;
        }
Exemple #23
0
        public static bool Online(int retryTime)
        {
            Ping ping = new Ping();
            PingOptions options = new PingOptions();
            options.DontFragment = true;
            PingReply reply;
            byte[] buffer = System.Text.Encoding.ASCII.GetBytes(string.Empty);

            int index = 0;

            while (index < retryTime)
            {
                try
                {
                    reply = ping.Send("www.baidu.com", 5000, buffer, options);

                    if (reply.Status.Equals(IPStatus.Success))
                        return true;
                }
                catch
                {
                    
                }

                index++;
            }

            return false;
        }
Exemple #24
0
        public static PingStatus Ping(string deviceName, PingerOptions options)
        {
            Ping pinger = new Ping();
            PingOptions pingOptions = new PingOptions() { DontFragment = options.DontFragment };
            
            // Create a buffer of 32 bytes of data to be transmitted.

            byte a = Encoding.ASCII.GetBytes("a")[0];
            byte[] buffer = new byte[options.PayloadSize]; // Encoding.ASCII.GetBytes(data);
            for (int i = 0; i < options.PayloadSize; i++)
            {
                buffer[i] = a;
            }

            try
            {
                PingReply reply = pinger.Send(deviceName, options.Timeout, buffer, pingOptions);
                if (reply.Status == IPStatus.Success)
                {
                    //Ping was successful
                    return new PingStatus(true, (int)reply.Status, reply.RoundtripTime);
                }
                //Ping failed
                return new PingStatus(false, (int)reply.Status, reply.RoundtripTime);
            }
            catch (Exception)
            {
                return new PingStatus(false, 99999, 99999);
            }
        }
Exemple #25
0
 public static bool TestConnection(string smtpServerAddress, int port)
 {
     Ping pingSender = new Ping();
     PingOptions options = new PingOptions();
     options.DontFragment = true;
     PingReply reply = null;
     try
     {
         reply = pingSender.Send(smtpServerAddress, 12000, Encoding.ASCII.GetBytes("SHIT"), options);
     }
     catch (System.Net.NetworkInformation.PingException)
     {
         return false;
     }
     if (reply.Status == IPStatus.Success)
     {
         IPHostEntry hostEntry = Dns.GetHostEntry(smtpServerAddress);
         IPEndPoint endPoint = new IPEndPoint(hostEntry.AddressList[0], port);
         using (Socket tcpSocket = new Socket(endPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp))
         {
             tcpSocket.Connect(endPoint);
             if (!CheckResponse(tcpSocket, 220))
                 return false;
             SendData(tcpSocket, string.Format("HELO {0}\r\n", Dns.GetHostName()));
             if (!CheckResponse(tcpSocket, 250))
                 return false;
             return true;
         }
     }
     else
         return false;
 }
        public string TargetFound(string target)
        {
            try
            {
                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(target, timeout, buffer, options);
                if (reply.Status == IPStatus.Success)
                {
                    return "targetfound";
                }
                else { return "targetnotfound"; }
            }
            catch(Exception e)
            {
                string CaughtException = e.ToString();
                return CaughtException.Substring(0, CaughtException.IndexOf(Environment.NewLine));
            }
        }
        public static bool CheckServerConnectivity(string ipAddress)
        {
            bool   connectionExists = false;
            string status           = "";

            try
            {
                System.Net.NetworkInformation.Ping        pingSender = new System.Net.NetworkInformation.Ping();
                System.Net.NetworkInformation.PingOptions options    = new System.Net.NetworkInformation.PingOptions();
                options.DontFragment = true;
                if (!string.IsNullOrEmpty(ipAddress))
                {
                    System.Net.NetworkInformation.PingReply reply = pingSender.Send(ipAddress);

                    connectionExists = reply.Status == System.Net.NetworkInformation.IPStatus.Success ? true : false;
                }
            }
            catch (PingException ex)
            {
                status = ex.Message.ToString();
            }
            catch (AggregateException ex)
            {
                foreach (Exception inner in ex.InnerExceptions)
                {
                    status = inner.Message.ToString();
                }
            }
            return(connectionExists);
        }
Exemple #28
0
 public pingObj()
 {
     pingSender = new Ping();
     options = new PingOptions();
     // Use the default Ttl value which is 128,
     // but change the fragmentation behavior.
     options.DontFragment = true;
 }
Exemple #29
0
 internal PingReply (IPAddress address, byte [] buffer, PingOptions options, long roundtripTime, IPStatus status)
 {
     this.address = address;
     this.buffer = buffer;
     this.options = options;
     this.rtt = roundtripTime;
     this.ipStatus = status;
 }
Exemple #30
0
		/// <summary>
		///     Sends a ping using IcmpSendEcho2Ex function in Iphlpapi.dll. Use this method when you need to specify a source
		///     interface for a ping otherwise use .NET ping implementation.
		/// </summary>
		/// <param name="srcAddress">The IPv4 source address on which to issue the echo request.</param>
		/// <param name="destAddress">The IPv4 destination of the echo request.</param>
		/// <param name="timeout">The time, in milliseconds, to wait for replies.</param>
		/// <param name="buffer">A buffer that contains data to send in the request.</param>
		/// <param name="po">IP header options for the request.</param>
		/// <exception cref="ArgumentNullException"></exception>
		/// <exception cref="FormatException">When the destination address is no valid IpV4 address or not defining a specific IP.</exception>
		public static PingReply SendPing(IPAddress srcAddress, IPAddress destAddress, int timeout = 5000, byte[] buffer = null, PingOptions po = null)
		{
			if (destAddress == null)
				throw new ArgumentNullException("destAddress");
			if (destAddress.AddressFamily != AddressFamily.InterNetwork || srcAddress.AddressFamily != AddressFamily.InterNetwork || destAddress.Equals(IPAddress.Any))
				throw new FormatException();

			//Defining p invoke arguments.
			var source = srcAddress == null ? 0 : BitConverter.ToUInt32(srcAddress.GetAddressBytes(), 0);
			var destination = BitConverter.ToUInt32(destAddress.GetAddressBytes(), 0);
			var sendbuffer = buffer ?? new byte[] {};
			var options = new Interop.Option
						{
							Ttl = (po == null ? (byte) 255 : (byte) po.Ttl),
							Flags = (po == null ? (byte) 0 : po.DontFragment ? (byte) 0x02 : (byte) 0) //0x02
						};
			var fullReplyBufferSize = Interop.ReplyMarshalLength + sendbuffer.Length; //Size of Reply structure plus the transmitted buffer length.



			var allocSpace = Marshal.AllocHGlobal(fullReplyBufferSize); // unmanaged allocation of reply size. TODO Maybe should be allocated on stack
			try
			{
				DateTime start = DateTime.Now;
				var nativeCode = Interop.IcmpSendEcho2Ex(
					Interop.IcmpHandle, //_In_      HANDLE IcmpHandle,
					default(IntPtr), //_In_opt_  HANDLE Event,
					default(IntPtr), //_In_opt_  PIO_APC_ROUTINE ApcRoutine,
					default(IntPtr), //_In_opt_  PVOID ApcContext
					source, //_In_      IPAddr SourceAddress,
					destination, //_In_      IPAddr DestinationAddress,
					sendbuffer, //_In_      LPVOID RequestData,
					(short) sendbuffer.Length, //_In_      WORD RequestSize,
					ref options, //_In_opt_  PIP_OPTION_INFORMATION RequestOptions,
					allocSpace, //_Out_     LPVOID ReplyBuffer,
					fullReplyBufferSize, //_In_      DWORD ReplySize,
					timeout //_In_      DWORD Timeout
					);
				TimeSpan duration = DateTime.Now - start;
				var reply = (Interop.Reply) Marshal.PtrToStructure(allocSpace, typeof (Interop.Reply)); // Parse the beginning of reply memory to reply structure

				byte[] replyBuffer = null;
				if (sendbuffer.Length != 0)
				{
					replyBuffer = new byte[sendbuffer.Length];
					Marshal.Copy(allocSpace + Interop.ReplyMarshalLength, replyBuffer, 0, sendbuffer.Length); //copy the rest of the reply memory to managed byte[]
				}

				if (nativeCode == 0) //Means that native method is faulted.
					return new PingReply(nativeCode, reply.Status, new IPAddress(reply.Address), duration);
				else
					return new PingReply(nativeCode, reply.Status, new IPAddress(reply.Address), reply.RoundTripTime, replyBuffer);
			}
			finally
			{
				Marshal.FreeHGlobal(allocSpace); //free allocated space
			}
		}
Exemple #31
0
        public static List<Hop> traceRoute(string ipAddrOrHostname, GatewayIPAddressInformation gateway, int minHops, int maxHops = 50, int timeout = 5000, byte[] buffer = null)
        {
            PingOptions pingOpts = new PingOptions();
            Stopwatch      watch = new Stopwatch();
            //pingOpts.Ttl = 1;   // only allow one hop initially

            // create default buffer to send if not specified
            if (buffer == null)
                buffer = new byte[32];

            List<Hop> hops = new List<Hop>();

            // Always do the first hop, so we can verify expected route is being used;
            // and if no interface was specified, well, its cheap anyway, since this is inside our PC
            if (doPing(0, hops, pingOpts, watch, ipAddrOrHostname, timeout, buffer))
            {
                // check it
                if (gateway!=null)
                {
                    if (!gateway.Address.ToString().Equals(hops[0].ip))
                    {
                        MessageBox.Show("WARNING: First hop" + hops[0].ip
                            + " didn't match intended gateway " + gateway.Address.ToString() + "; try 'route print'.");
                    }
                }
            }
            else
            {
                // stop
                if (gateway != null)
                {
                    MessageBox.Show("Gateway " + gateway.Address.ToString() + " down?");
                }
                else
                {
                    MessageBox.Show(hops[0].ip);
                }
                return hops;
            }

            if (minHops > 0)
            {
                // prefill
                for (int i = 1; i < minHops; i++)
                {
                    hops.Add(new Hop(i, "Dummy entry", -1, false));
                }
            }
            int start = Math.Max(minHops, 1);
            for (int i = start; i < maxHops; i++)
            {
                if (!doPing(i, hops, pingOpts, watch, ipAddrOrHostname,   timeout ,  buffer)) {
                    // stop
                    break;
                }
            }
            return hops;
        }
Exemple #32
0
        public bool PingTest(string strURL)
        {
            System.Net.NetworkInformation.Ping        objPing    = new System.Net.NetworkInformation.Ping();
            System.Net.NetworkInformation.PingOptions objOptions = new System.Net.NetworkInformation.PingOptions();
            objOptions.DontFragment = true;

            try{
                System.Net.NetworkInformation.PingReply objReply = objPing.Send(strURL, 4);
                return(true);
            }
            catch (SystemException e)
            {
                return(false);
            }
        }
Exemple #33
0
        private static PingReply DoPing(string AddressToPing)
        {
            //we dont really care about the data
            string data = "This is a ping test";

            byte[] buffer = Encoding.ASCII.GetBytes(data);

            int timeout = 1024;

            System.Net.NetworkInformation.Ping        sendPing = new System.Net.NetworkInformation.Ping();
            System.Net.NetworkInformation.PingOptions options  = new System.Net.NetworkInformation.PingOptions
            {
                DontFragment = true
            };
            System.Net.NetworkInformation.PingReply reply = sendPing.Send(AddressToPing, timeout, buffer, options);
            return(reply);
        }
Exemple #34
0
        public bool Ping(string ip)
        {
            System.Net.NetworkInformation.Ping        p       = new System.Net.NetworkInformation.Ping();
            System.Net.NetworkInformation.PingOptions options = new System.Net.NetworkInformation.PingOptions();
            options.DontFragment = true;
            string data = "Test Data!";

            byte[] buffer  = Encoding.ASCII.GetBytes(data);
            int    timeout = 1000; // Timeout 时间,单位:毫秒

            System.Net.NetworkInformation.PingReply reply = p.Send(ip, timeout, buffer, options);
            if (reply.Status == System.Net.NetworkInformation.IPStatus.Success)
            {
                return(true);
            }
            else
            {
                return(false);
            }
        }
Exemple #35
0
        private static void pingThread()
        {
            while (true)
            {
                try
                {
                    foreach (virtualUser User in _Users)
                    {
                        if (User.pingOK)
                        {
                            try
                            {
                                byte[] buffer = new byte[32];
                                System.Net.NetworkInformation.PingOptions pingOptions = new System.Net.NetworkInformation.PingOptions(128, true);
                                System.Net.NetworkInformation.Ping        ping        = new System.Net.NetworkInformation.Ping();
                                System.Net.NetworkInformation.PingReply   pingReply   = ping.Send(((IPEndPoint)User.uSocket.RemoteEndPoint).Address, 75, buffer, pingOptions);

                                if (pingReply != null)
                                {
                                    switch (pingReply.Status)
                                    {
                                    case System.Net.NetworkInformation.IPStatus.Success:
                                        User.Ping = pingReply.RoundtripTime;
                                        break;
                                    }
                                }
                            }
                            catch
                            {
                            }
                            User.pingOK = false;
                            User.send(new PACKET_PING(User));
                        }
                    }
                }
                catch { }
                Thread.Sleep(2500);
            }
        }
Exemple #36
0
 /// <summary>
 /// check the net
 /// </summary>
 /// <param name="ip"></param>
 /// <returns></returns>
 private bool Ping(string ip)
 {
     try
     {
         System.Net.NetworkInformation.Ping        p       = new System.Net.NetworkInformation.Ping();
         System.Net.NetworkInformation.PingOptions options = new System.Net.NetworkInformation.PingOptions();
         int timeout = 1000; // Timeout 时间,单位:毫秒
         System.Net.NetworkInformation.PingReply reply = p.Send(ip, timeout);
         if (reply.Status == System.Net.NetworkInformation.IPStatus.Success)
         {
             return(true);
         }
         else
         {
             return(false);
         }
     }
     catch
     {
         return(false);
     }
 }
Exemple #37
0
        private PingReply SendUnprivileged(IPAddress address, int timeout, byte [] buffer, PingOptions options)
        {
#if MONO_FEATURE_PROCESS_START
            DateTime sentTime = DateTime.UtcNow;

            Process ping      = new Process();
            string  args      = BuildPingArgs(address, timeout, options);
            long    trip_time = 0;

            ping.StartInfo.FileName  = PingBinPath;
            ping.StartInfo.Arguments = args;

            ping.StartInfo.CreateNoWindow  = true;
            ping.StartInfo.UseShellExecute = false;

            ping.StartInfo.RedirectStandardOutput = true;
            ping.StartInfo.RedirectStandardError  = true;

            IPStatus status = IPStatus.Unknown;
            try {
                ping.Start();

#pragma warning disable 219
                string stdout = ping.StandardOutput.ReadToEnd();
                string stderr = ping.StandardError.ReadToEnd();
#pragma warning restore 219

                trip_time = (long)(DateTime.UtcNow - sentTime).TotalMilliseconds;
                if (!ping.WaitForExit(timeout) || (ping.HasExited && ping.ExitCode == 2))
                {
                    status = IPStatus.TimedOut;
                }
                else if (ping.ExitCode == 0)
                {
                    status = IPStatus.Success;
                }
                else if (ping.ExitCode == 1)
                {
                    status = IPStatus.TtlExpired;
                }
            } catch {
            } finally {
                if (!ping.HasExited)
                {
                    ping.Kill();
                }
                ping.Dispose();
            }

            return(new PingReply(address, buffer, options, trip_time, status));
#else
            throw new PlatformNotSupportedException("Ping is not supported on this platform.");
#endif // MONO_FEATURE_PROCESS_START
        }
Exemple #38
0
 public PingReply Send(string hostNameOrAddress, int timeout, byte [] buffer, PingOptions options)
 {
     IPAddress [] addresses = Dns.GetHostAddresses(hostNameOrAddress);
     return(Send(addresses [0], timeout, buffer, options));
 }
Exemple #39
0
        private async Task <PingReply> SendWithPingUtility(IPAddress address, byte[] buffer, int timeout, PingOptions options)
        {
            bool   isIpv4         = address.AddressFamily == AddressFamily.InterNetwork;
            string pingExecutable = isIpv4 ? UnixCommandLinePing.Ping4UtilityPath : UnixCommandLinePing.Ping6UtilityPath;

            if (pingExecutable == null)
            {
                throw new PlatformNotSupportedException(SR.net_ping_utility_not_found);
            }

            string           processArgs = UnixCommandLinePing.ConstructCommandLine(buffer.Length, address.ToString(), isIpv4);
            ProcessStartInfo psi         = new ProcessStartInfo(pingExecutable, processArgs);

            psi.RedirectStandardOutput = true;
            psi.RedirectStandardError  = true;
            Process p = new Process()
            {
                StartInfo = psi
            };

            var processCompletion = new TaskCompletionSource <bool>(TaskCreationOptions.RunContinuationsAsynchronously);

            p.EnableRaisingEvents = true;
            p.Exited += (s, e) => processCompletion.SetResult(true);
            p.Start();
            var  cts         = new CancellationTokenSource();
            Task timeoutTask = Task.Delay(timeout, cts.Token);

            Task finished = await Task.WhenAny(processCompletion.Task, timeoutTask).ConfigureAwait(false);

            if (finished == timeoutTask && !p.HasExited)
            {
                // Try to kill the ping process if it didn't return. If it is already in the process of exiting, a Win32Exception will be thrown.
                try
                {
                    p.Kill();
                }
                catch (Win32Exception) { }
                return(CreateTimedOutPingReply());
            }
            else
            {
                cts.Cancel();
                if (p.ExitCode != 0)
                {
                    // This means no reply was received, although transmission may have been successful.
                    return(CreateTimedOutPingReply());
                }

                try
                {
                    string output = await p.StandardOutput.ReadToEndAsync().ConfigureAwait(false);

                    long rtt = UnixCommandLinePing.ParseRoundTripTime(output);
                    return(new PingReply(
                               address,
                               null, // Ping utility cannot accomodate these, return null to indicate they were ignored.
                               IPStatus.Success,
                               rtt,
                               Array.Empty <byte>())); // Ping utility doesn't deliver this info.
                }
                catch (Exception)
                {
                    // If the standard output cannot be successfully parsed, throw a generic PingException.
                    throw new PingException(SR.net_ping);
                }
            }
        }
Exemple #40
0
        private async Task <PingReply> SendIcmpEchoRequestOverRawSocket(IPAddress address, byte[] buffer, int timeout, PingOptions options)
        {
            EndPoint endPoint = new IPEndPoint(address, 0);

            bool         isIpv4       = address.AddressFamily == AddressFamily.InterNetwork;
            ProtocolType protocolType = isIpv4 ? ProtocolType.Icmp : ProtocolType.IcmpV6;
            // Use the current thread's ID as the identifier.
            ushort     identifier = (ushort)Environment.CurrentManagedThreadId;
            IcmpHeader header     = new IcmpHeader()
            {
                Type           = isIpv4 ? (byte)IcmpV4MessageType.EchoRequest : (byte)IcmpV6MessageType.EchoRequest,
                Code           = 0,
                HeaderChecksum = 0,
                Identifier     = identifier,
                SequenceNumber = 0,
            };

            byte[] sendBuffer = CreateSendMessageBuffer(header, buffer);

            using (Socket socket = new Socket(address.AddressFamily, SocketType.Raw, protocolType))
            {
                socket.ReceiveTimeout = timeout;
                socket.SendTimeout    = timeout;
                // Setting Socket.DontFragment and .Ttl is not supported on Unix, so ignore the PingOptions parameter.

                int ipHeaderLength = isIpv4 ? IpHeaderLengthInBytes : 0;
                await socket.SendToAsync(new ArraySegment <byte>(sendBuffer), SocketFlags.None, endPoint).ConfigureAwait(false);

                byte[] receiveBuffer = new byte[ipHeaderLength + IcmpHeaderLengthInBytes + buffer.Length];

                long      elapsed;
                Stopwatch sw = Stopwatch.StartNew();
                // Read from the socket in a loop. We may receive messages that are not echo replies, or that are not in response
                // to the echo request we just sent. We need to filter such messages out, and continue reading until our timeout.
                // For example, when pinging the local host, we need to filter out our own echo requests that the socket reads.
                while ((elapsed = sw.ElapsedMilliseconds) < timeout)
                {
                    Task <SocketReceiveFromResult> receiveTask = socket.ReceiveFromAsync(
                        new ArraySegment <byte>(receiveBuffer),
                        SocketFlags.None,
                        endPoint);
                    var  cts      = new CancellationTokenSource();
                    Task finished = await Task.WhenAny(receiveTask, Task.Delay(timeout - (int)elapsed, cts.Token)).ConfigureAwait(false);

                    cts.Cancel();
                    if (finished != receiveTask)
                    {
                        sw.Stop();
                        return(CreateTimedOutPingReply());
                    }

                    SocketReceiveFromResult receiveResult = receiveTask.GetAwaiter().GetResult();
                    int bytesReceived = receiveResult.ReceivedBytes;
                    if (bytesReceived - ipHeaderLength < IcmpHeaderLengthInBytes)
                    {
                        continue; // Not enough bytes to reconstruct IP header + ICMP header.
                    }

                    byte type, code;
                    unsafe
                    {
                        fixed(byte *bytesPtr = receiveBuffer)
                        {
                            int        icmpHeaderOffset = ipHeaderLength;
                            IcmpHeader receivedHeader   = *((IcmpHeader *)(bytesPtr + icmpHeaderOffset)); // Skip IP header.

                            type = receivedHeader.Type;
                            code = receivedHeader.Code;

                            if (identifier != receivedHeader.Identifier ||
                                type == (byte)IcmpV4MessageType.EchoRequest ||
                                type == (byte)IcmpV6MessageType.EchoRequest)    // Echo Request, ignore
                            {
                                continue;
                            }
                        }
                    }

                    sw.Stop();
                    long roundTripTime = sw.ElapsedMilliseconds;
                    int  dataOffset    = ipHeaderLength + IcmpHeaderLengthInBytes;
                    // We want to return a buffer with the actual data we sent out, not including the header data.
                    byte[] dataBuffer = new byte[bytesReceived - dataOffset];
                    Array.Copy(receiveBuffer, dataOffset, dataBuffer, 0, dataBuffer.Length);

                    IPStatus status = isIpv4
                                        ? IcmpV4MessageConstants.MapV4TypeToIPStatus(type, code)
                                        : IcmpV6MessageConstants.MapV6TypeToIPStatus(type, code);

                    return(new PingReply(address, options, status, roundTripTime, dataBuffer));
                }

                // We have exceeded our timeout duration, and no reply has been received.
                sw.Stop();
                return(CreateTimedOutPingReply());
            }
        }
Exemple #41
0
 private async Task <PingReply> SendPingAsyncCore(IPAddress address, byte[] buffer, int timeout, PingOptions options)
 {
     try
     {
         Task <PingReply> t = RawSocketPermissions.CanUseRawSockets() ?
                              SendIcmpEchoRequestOverRawSocket(address, buffer, timeout, options) :
                              SendWithPingUtility(address, buffer, timeout, options);
         return(await t.ConfigureAwait(false));
     }
     finally
     {
         Finish();
     }
 }
Exemple #42
0
        private SocketConfig GetSocketConfig(IPAddress address, byte[] buffer, int timeout, PingOptions options)
        {
            SocketConfig config = new SocketConfig();

            config.EndPoint = new IPEndPoint(address, 0);
            config.Timeout  = timeout;
            config.Options  = options;

            config.IsIpv4       = address.AddressFamily == AddressFamily.InterNetwork;
            config.ProtocolType = config.IsIpv4 ? ProtocolType.Icmp : ProtocolType.IcmpV6;

            // Use a random value as the identifier. This doesn't need to be perfectly random
            // or very unpredictable, rather just good enough to avoid unexpected conflicts.
            Random rand = t_idGenerator ?? (t_idGenerator = new Random());

            config.Identifier = (ushort)rand.Next((int)ushort.MaxValue + 1);

            IcmpHeader header = new IcmpHeader()
            {
                Type           = config.IsIpv4 ? (byte)IcmpV4MessageType.EchoRequest : (byte)IcmpV6MessageType.EchoRequest,
                Code           = 0,
                HeaderChecksum = 0,
                Identifier     = config.Identifier,
                SequenceNumber = 0,
            };

            config.SendBuffer = CreateSendMessageBuffer(header, buffer);
            return(config);
        }
Exemple #43
0
 /// <summary>
 /// 尝试用指定的数据缓冲区以异步方式将 Internet 控制消息协议 (ICMP) 回显消息发送到具有指定的 System.Net.IPAddress
 /// 的计算机,并从该计算机接收对应的 ICMP 回显回复消息。此重载允许您指定操作的超时值,并控制 ICMP 回显消息数据包的碎片和生存时间值。
 /// </summary>
 /// <param name="address">标识 ICMP 回送消息目标计算机的 System.Net.IPAddress。</param>
 /// <param name="times">Ping命令发送次数。</param>
 /// <param name="timeout">一个 System.Byte 数组,它包含要与 ICMP 回送消息一起发送并在 ICMP 回送应答消息中返回的数据。该数组包含的字节数不能超过 65,500个字节。</param>
 /// <param name="buffer">一个 System.Byte 数组,它包含要与 ICMP 回送消息一起发送并在 ICMP 回送应答消息中返回的数据。该数组包含的字节数不能超过 65,500个字节</param>
 /// <param name="options">一个 System.Net.NetworkInformation.PingOptions 对象,用于控制 ICMP 回显消息数据包的碎片和生存时间值。</param>
 /// <param name="userToken">一个对象,此对象将被传递给异步操作完成后所调用的方法。</param>
 public void SendAsync(IPAddress address, Int32 times, Int32 timeout, Byte[] buffer, PingOptions options, Object userToken)
 {
     SendAsync(address.ToString(), times, timeout, buffer, options, userToken);
 }
Exemple #44
0
        public void SendAsync(string hostNameOrAddress, int timeout, byte [] buffer, PingOptions options, object userToken)
        {
            IPAddress address = Dns.GetHostEntry(hostNameOrAddress).AddressList [0];

            SendAsync(address, timeout, buffer, options, userToken);
        }
Exemple #45
0
        private PingReply SendPrivileged(IPAddress address, int timeout, byte [] buffer, PingOptions options)
        {
            IPEndPoint target = new IPEndPoint(address, 0);
            IPEndPoint client = new IPEndPoint(GetNonLoopbackIP(), 0);

            // FIXME: support IPv6
            using (Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Raw, ProtocolType.Icmp)) {
                if (options != null)
                {
                    s.DontFragment = options.DontFragment;
                    s.Ttl          = (short)options.Ttl;
                }
                s.SendTimeout    = timeout;
                s.ReceiveTimeout = timeout;
                // not sure why Identifier = 0 is unacceptable ...
                IcmpMessage send  = new IcmpMessage(8, 0, identifier, 0, buffer);
                byte []     bytes = send.GetBytes();
                s.SendBufferSize = bytes.Length;
                s.SendTo(bytes, bytes.Length, SocketFlags.None, target);

                DateTime sentTime = DateTime.Now;

                // receive
                bytes = new byte [100];
                do
                {
                    EndPoint    endpoint = client;
                    SocketError error    = 0;
                    int         rc       = s.ReceiveFrom(bytes, 0, 100, SocketFlags.None,
                                                         ref endpoint, out error);

                    if (error != SocketError.Success)
                    {
                        if (error == SocketError.TimedOut)
                        {
                            return(new PingReply(null, new byte [0], options, 0, IPStatus.TimedOut));
                        }
                        throw new NotSupportedException(String.Format("Unexpected socket error during ping request: {0}", error));
                    }
                    long rtt          = (long)(DateTime.Now - sentTime).TotalMilliseconds;
                    int  headerLength = (bytes [0] & 0xF) << 2;
                    int  bodyLength   = rc - headerLength;

                    // Ping reply to different request. discard it.
                    if (!((IPEndPoint)endpoint).Address.Equals(target.Address))
                    {
                        long t = timeout - rtt;
                        if (t <= 0)
                        {
                            return(new PingReply(null, new byte [0], options, 0, IPStatus.TimedOut));
                        }
                        s.ReceiveTimeout = (int)t;
                        continue;
                    }

                    IcmpMessage recv = new IcmpMessage(bytes, headerLength, bodyLength);

                    /* discard ping reply to different request or echo requests if running on same host. */
                    if (recv.Identifier != identifier || recv.Type == 8)
                    {
                        long t = timeout - rtt;
                        if (t <= 0)
                        {
                            return(new PingReply(null, new byte [0], options, 0, IPStatus.TimedOut));
                        }
                        s.ReceiveTimeout = (int)t;
                        continue;
                    }

                    return(new PingReply(address, recv.Data, options, rtt, recv.IPStatus));
                } while (true);
            }
        }
Exemple #46
0
        private PingReply SendUnprivileged(IPAddress address, int timeout, byte [] buffer, PingOptions options)
        {
            DateTime sentTime = DateTime.Now;

            Process ping      = new Process();
            string  args      = BuildPingArgs(address, timeout, options);
            long    trip_time = 0;

            ping.StartInfo.FileName  = PingBinPath;
            ping.StartInfo.Arguments = args;

            ping.StartInfo.CreateNoWindow  = true;
            ping.StartInfo.UseShellExecute = false;

            ping.StartInfo.RedirectStandardOutput = true;
            ping.StartInfo.RedirectStandardError  = true;

            try
            {
                ping.Start();

#pragma warning disable 219
                string stdout = ping.StandardOutput.ReadToEnd();
                string stderr = ping.StandardError.ReadToEnd();
#pragma warning restore 219

                trip_time = (long)(DateTime.Now - sentTime).TotalMilliseconds;
                if (!ping.WaitForExit(timeout) || (ping.HasExited && ping.ExitCode == 2))
                {
                    return(new PingReply(address, buffer, options, trip_time, IPStatus.TimedOut));
                }

                if (ping.ExitCode == 1)
                {
                    return(new PingReply(address, buffer, options, trip_time, IPStatus.TtlExpired));
                }
            }
            catch (Exception)
            {
                return(new PingReply(address, buffer, options, trip_time, IPStatus.Unknown));
            }
            finally
            {
                if (ping != null)
                {
                    if (!ping.HasExited)
                    {
                        ping.Kill();
                    }
                    ping.Dispose();
                }
            }

            return(new PingReply(address, buffer, options, trip_time, IPStatus.Success));
        }
Exemple #47
0
        public Task <PingReply> SendPingAsync(string hostNameOrAddress, int timeout, byte[] buffer, PingOptions options)
        {
            if (string.IsNullOrEmpty(hostNameOrAddress))
            {
                throw new ArgumentNullException(nameof(hostNameOrAddress));
            }

            IPAddress address;

            if (IPAddress.TryParse(hostNameOrAddress, out address))
            {
                return(SendPingAsync(address, timeout, buffer, options));
            }

            if (buffer == null)
            {
                throw new ArgumentNullException(nameof(buffer));
            }

            if (buffer.Length > MaxBufferSize)
            {
                throw new ArgumentException(SR.net_invalidPingBufferSize, nameof(buffer));
            }

            if (timeout < 0)
            {
                throw new ArgumentOutOfRangeException(nameof(timeout));
            }

            CheckStart();
            return(GetAddressAndSendAsync(hostNameOrAddress, timeout, buffer, options));
        }
Exemple #48
0
        private async Task <PingReply> SendIcmpEchoRequestOverRawSocketAsync(IPAddress address, byte[] buffer, int timeout, PingOptions options)
        {
            SocketConfig socketConfig = GetSocketConfig(address, buffer, timeout, options);

            using (Socket socket = GetRawSocket(socketConfig))
            {
                int ipHeaderLength = socketConfig.IsIpv4 ? MinIpHeaderLengthInBytes : 0;

                await socket.SendToAsync(
                    new ArraySegment <byte>(socketConfig.SendBuffer),
                    SocketFlags.None, socketConfig.EndPoint)
                .ConfigureAwait(false);

                byte[] receiveBuffer = new byte[MaxIpHeaderLengthInBytes + IcmpHeaderLengthInBytes + buffer.Length];

                long      elapsed;
                Stopwatch sw = Stopwatch.StartNew();
                // Read from the socket in a loop. We may receive messages that are not echo replies, or that are not in response
                // to the echo request we just sent. We need to filter such messages out, and continue reading until our timeout.
                // For example, when pinging the local host, we need to filter out our own echo requests that the socket reads.
                while ((elapsed = sw.ElapsedMilliseconds) < timeout)
                {
                    Task <SocketReceiveFromResult> receiveTask = socket.ReceiveFromAsync(
                        new ArraySegment <byte>(receiveBuffer),
                        SocketFlags.None,
                        socketConfig.EndPoint);

                    var  cts      = new CancellationTokenSource();
                    Task finished = await Task.WhenAny(receiveTask, Task.Delay(timeout - (int)elapsed, cts.Token)).ConfigureAwait(false);

                    cts.Cancel();
                    if (finished != receiveTask)
                    {
                        return(CreateTimedOutPingReply());
                    }

                    SocketReceiveFromResult receiveResult = receiveTask.GetAwaiter().GetResult();
                    int bytesReceived = receiveResult.ReceivedBytes;
                    if (bytesReceived - ipHeaderLength < IcmpHeaderLengthInBytes)
                    {
                        continue; // Not enough bytes to reconstruct IP header + ICMP header.
                    }

                    if (TryGetPingReply(socketConfig, receiveBuffer, bytesReceived, sw, ref ipHeaderLength, out PingReply reply))
                    {
                        return(reply);
                    }
                }

                // We have exceeded our timeout duration, and no reply has been received.
                return(CreateTimedOutPingReply());
            }
        }
Exemple #49
0
        private PingReply SendPingCore(IPAddress address, byte[] buffer, int timeout, PingOptions options)
        {
            try
            {
                PingReply reply = RawSocketPermissions.CanUseRawSockets(address.AddressFamily) ?
                                  SendIcmpEchoRequestOverRawSocket(address, buffer, timeout, options) :
                                  SendWithPingUtility(address, buffer, timeout, options);

                return(reply);
            }
            finally
            {
                Finish();
            }
        }
Exemple #50
0
        private PingReply SendWithPingUtility(IPAddress address, byte[] buffer, int timeout, PingOptions options)
        {
            using (Process p = GetPingProcess(address, buffer, options))
            {
                p.Start();
                if (!p.WaitForExit(timeout) || p.ExitCode == 1 || p.ExitCode == 2)
                {
                    return(CreateTimedOutPingReply());
                }

                try
                {
                    string output = p.StandardOutput.ReadToEnd();
                    return(ParsePingUtilityOutput(address, output));
                }
                catch (Exception)
                {
                    // If the standard output cannot be successfully parsed, throw a generic PingException.
                    throw new PingException(SR.net_ping);
                }
            }
        }
Exemple #51
0
        public Task <PingReply> SendPingAsync(IPAddress address, int timeout, byte [] buffer, PingOptions options)
        {
            if ((worker != null) || (cts != null))
            {
                throw new InvalidOperationException("Another SendAsync operation is in progress");
            }

            cts = new CancellationTokenSource();

            var task = Task <PingReply> .Factory.StartNew(
                () => Send (address, timeout, buffer, options), cts.Token);

            task.ContinueWith((t) => {
                if (t.IsCanceled)
                {
                    OnPingCompleted(new PingCompletedEventArgs(null, true, null, null));
                }
                else if (t.IsFaulted)
                {
                    OnPingCompleted(new PingCompletedEventArgs(t.Exception, false, null, null));
                }
                else
                {
                    OnPingCompleted(new PingCompletedEventArgs(null, false, null, t.Result));
                }
            });

            return(task);
        }
Exemple #52
0
        public Task <PingReply> SendPingAsync(string hostNameOrAddress, int timeout, byte [] buffer, PingOptions options)
        {
            IPAddress address = Dns.GetHostEntry(hostNameOrAddress).AddressList [0];

            return(SendPingAsync(address, timeout, buffer, options));
        }
Exemple #53
0
        private async Task <PingReply> GetAddressAndSendAsync(string hostNameOrAddress, int timeout, byte[] buffer, PingOptions options)
        {
            bool requiresFinish = true;

            try
            {
                IPAddress[] addresses = await Dns.GetHostAddressesAsync(hostNameOrAddress).ConfigureAwait(false);

                Task <PingReply> pingReplyTask = SendPingAsyncCore(addresses[0], buffer, timeout, options);
                requiresFinish = false;
                return(await pingReplyTask.ConfigureAwait(false));
            }
            catch (Exception e)
            {
                // SendPingAsyncCore will call Finish before completing the Task.  If SendPingAsyncCore isn't invoked
                // because an exception is thrown first, or if it throws out an exception synchronously, then
                // we need to invoke Finish; otherwise, it has the responsibility to invoke Finish.
                if (requiresFinish)
                {
                    Finish();
                }
                throw new PingException(SR.net_ping, e);
            }
        }
Exemple #54
0
        private PingReply SendIcmpEchoRequestOverRawSocket(IPAddress address, byte[] buffer, int timeout, PingOptions options)
        {
            SocketConfig socketConfig = GetSocketConfig(address, buffer, timeout, options);

            using (Socket socket = GetRawSocket(socketConfig))
            {
                int ipHeaderLength = socketConfig.IsIpv4 ? MinIpHeaderLengthInBytes : 0;
                try
                {
                    socket.SendTo(socketConfig.SendBuffer, SocketFlags.None, socketConfig.EndPoint);
                }
                catch (SocketException ex) when(ex.SocketErrorCode == SocketError.TimedOut)
                {
                    return(CreateTimedOutPingReply());
                }

                byte[] receiveBuffer = new byte[MaxIpHeaderLengthInBytes + IcmpHeaderLengthInBytes + buffer.Length];

                long      elapsed;
                Stopwatch sw = Stopwatch.StartNew();
                // Read from the socket in a loop. We may receive messages that are not echo replies, or that are not in response
                // to the echo request we just sent. We need to filter such messages out, and continue reading until our timeout.
                // For example, when pinging the local host, we need to filter out our own echo requests that the socket reads.
                while ((elapsed = sw.ElapsedMilliseconds) < timeout)
                {
                    int bytesReceived;
                    try
                    {
                        bytesReceived = socket.ReceiveFrom(receiveBuffer, SocketFlags.None, ref socketConfig.EndPoint);
                    }
                    catch (SocketException ex) when(ex.SocketErrorCode == SocketError.TimedOut)
                    {
                        return(CreateTimedOutPingReply());
                    }

                    if (bytesReceived - ipHeaderLength < IcmpHeaderLengthInBytes)
                    {
                        continue; // Not enough bytes to reconstruct IP header + ICMP header.
                    }

                    if (TryGetPingReply(socketConfig, receiveBuffer, bytesReceived, sw, ref ipHeaderLength, out PingReply reply))
                    {
                        return(reply);
                    }
                }

                // We have exceeded our timeout duration, and no reply has been received.
                return(CreateTimedOutPingReply());
            }
        }
Exemple #55
0
        public Task <PingReply> SendPingAsync(IPAddress address, int timeout, byte[] buffer, PingOptions options)
        {
            if (buffer == null)
            {
                throw new ArgumentNullException(nameof(buffer));
            }

            if (buffer.Length > MaxBufferSize)
            {
                throw new ArgumentException(SR.net_invalidPingBufferSize, nameof(buffer));
            }

            if (timeout < 0)
            {
                throw new ArgumentOutOfRangeException(nameof(timeout));
            }

            if (address == null)
            {
                throw new ArgumentNullException(nameof(address));
            }

            // Check if address family is installed.
            TestIsIpSupported(address);

            if (address.Equals(IPAddress.Any) || address.Equals(IPAddress.IPv6Any))
            {
                throw new ArgumentException(SR.net_invalid_ip_addr, nameof(address));
            }

            // Need to snapshot the address here, so we're sure that it's not changed between now
            // and the operation, and to be sure that IPAddress.ToString() is called and not some override.
            IPAddress addressSnapshot = (address.AddressFamily == AddressFamily.InterNetwork) ?
                                        new IPAddress(address.GetAddressBytes()) :
                                        new IPAddress(address.GetAddressBytes(), address.ScopeId);

            CheckStart();
            try
            {
                return(SendPingAsyncCore(addressSnapshot, buffer, timeout, options));
            }
            catch (Exception e)
            {
                Finish();
                return(Task.FromException <PingReply>(new PingException(SR.net_ping, e)));
            }
        }
Exemple #56
0
        public void SendAsync(IPAddress ipAddress, PingOptions pingOptions, CancellationToken cancellationToken)
        {
            Task.Run(() =>
            {
                var hostname = pingOptions.Hostname;

                // Try to resolve PTR
                if (string.IsNullOrEmpty(hostname))
                {
                    try
                    {
                        Task.Run(() =>
                        {
                            hostname = Dns.GetHostEntryAsync(ipAddress).Result.HostName;
                        }, cancellationToken);
                    }
                    catch (SocketException) { }
                }

                var pingTotal  = 0;
                var errorCount = 0;

                var options = new System.Net.NetworkInformation.PingOptions
                {
                    Ttl          = pingOptions.TTL,
                    DontFragment = pingOptions.DontFragment
                };

                using (var ping = new System.Net.NetworkInformation.Ping())
                {
                    do
                    {
                        try
                        {
                            // Get timestamp
                            var timestamp = DateTime.Now;

                            // Send ping
                            var pingReply = ping.Send(ipAddress, pingOptions.Timeout, pingOptions.Buffer, options);

                            // Reset the error count (if no exception was thrown)
                            errorCount = 0;

                            if (pingReply == null || pingReply.Status != IPStatus.Success)
                            {
                                if (pingReply != null && pingReply.Address == null)
                                {
                                    OnPingReceived(new PingReceivedArgs(timestamp, ipAddress, hostname, pingReply.Status));
                                }
                                else if (pingReply != null)
                                {
                                    OnPingReceived(new PingReceivedArgs(timestamp, pingReply.Address, hostname, pingReply.Status));
                                }
                            }
                            else
                            {
                                if (ipAddress.AddressFamily == AddressFamily.InterNetwork)
                                {
                                    OnPingReceived(new PingReceivedArgs(timestamp, pingReply.Address, hostname,
                                                                        pingReply.Buffer.Length, pingReply.RoundtripTime, pingReply.Options.Ttl, pingReply.Status));
                                }
                                else
                                {
                                    OnPingReceived(new PingReceivedArgs(timestamp, pingReply.Address, hostname,
                                                                        pingReply.Buffer.Length, pingReply.RoundtripTime, pingReply.Status));
                                }
                            }
                        }
                        catch (PingException ex)
                        {
                            errorCount++;

                            if (errorCount == pingOptions.ExceptionCancelCount)
                            {
                                OnPingException(new PingExceptionArgs(ex.Message, ex.InnerException));

                                break;
                            }
                        }

                        pingTotal++;

                        // If ping is canceled... dont wait for example 5 seconds
                        for (var i = 0; i < pingOptions.WaitTime; i += 100)
                        {
                            Thread.Sleep(100);

                            if (cancellationToken.IsCancellationRequested)
                            {
                                break;
                            }
                        }
                    } while ((pingOptions.Attempts == 0 || pingTotal < pingOptions.Attempts) && !cancellationToken.IsCancellationRequested);
                }

                if (cancellationToken.IsCancellationRequested)
                {
                    OnUserHasCanceled();
                }
                else
                {
                    OnPingCompleted();
                }
            }, cancellationToken);
        }
        // Any exceptions that escape synchronously will be caught by the caller and wrapped in a PingException.
        // We do not need to or want to capture such exceptions into the returned task.
        private Task <PingReply> SendPingAsyncCore(IPAddress address, byte[] buffer, int timeout, PingOptions options)
        {
            var tcs = new TaskCompletionSource <PingReply>();

            _taskCompletionSource = tcs;

            _ipv6     = (address.AddressFamily == AddressFamily.InterNetworkV6);
            _sendSize = buffer.Length;

            // Get and cache correct handle.
            if (!_ipv6 && _handlePingV4 == null)
            {
                _handlePingV4 = Interop.IpHlpApi.IcmpCreateFile();
                if (_handlePingV4.IsInvalid)
                {
                    _handlePingV4 = null;
                    throw new Win32Exception(); // Gets last error.
                }
            }
            else if (_ipv6 && _handlePingV6 == null)
            {
                _handlePingV6 = Interop.IpHlpApi.Icmp6CreateFile();
                if (_handlePingV6.IsInvalid)
                {
                    _handlePingV6 = null;
                    throw new Win32Exception(); // Gets last error.
                }
            }

            var ipOptions = new Interop.IpHlpApi.IPOptions(options);

            if (_replyBuffer == null)
            {
                _replyBuffer = SafeLocalAllocHandle.LocalAlloc(MaxUdpPacket);
            }

            // Queue the event.
            int error;

            try
            {
                if (_pingEvent == null)
                {
                    _pingEvent = new ManualResetEvent(false);
                }
                else
                {
                    _pingEvent.Reset();
                }

                _registeredWait = ThreadPool.RegisterWaitForSingleObject(_pingEvent, (state, _) => ((Ping)state).PingCallback(), this, -1, true);

                SetUnmanagedStructures(buffer);

                if (!_ipv6)
                {
                    SafeWaitHandle pingEventSafeWaitHandle = _pingEvent.GetSafeWaitHandle();
                    error = (int)Interop.IpHlpApi.IcmpSendEcho2(
                        _handlePingV4,
                        pingEventSafeWaitHandle,
                        IntPtr.Zero,
                        IntPtr.Zero,
                        (uint)address.GetAddress(),
                        _requestBuffer,
                        (ushort)buffer.Length,
                        ref ipOptions,
                        _replyBuffer,
                        MaxUdpPacket,
                        (uint)timeout);
                }
                else
                {
                    IPEndPoint ep = new IPEndPoint(address, 0);
                    Internals.SocketAddress remoteAddr = IPEndPointExtensions.Serialize(ep);
                    byte[] sourceAddr = new byte[28];

                    SafeWaitHandle pingEventSafeWaitHandle = _pingEvent.GetSafeWaitHandle();
                    error = (int)Interop.IpHlpApi.Icmp6SendEcho2(
                        _handlePingV6,
                        pingEventSafeWaitHandle,
                        IntPtr.Zero,
                        IntPtr.Zero,
                        sourceAddr,
                        remoteAddr.Buffer,
                        _requestBuffer,
                        (ushort)buffer.Length,
                        ref ipOptions,
                        _replyBuffer,
                        MaxUdpPacket,
                        (uint)timeout);
                }
            }
            catch
            {
                UnregisterWaitHandle();
                throw;
            }

            if (error == 0)
            {
                error = Marshal.GetLastWin32Error();

                // Only skip Async IO Pending error value.
                if (error != Interop.IpHlpApi.ERROR_IO_PENDING)
                {
                    // Cleanup.
                    FreeUnmanagedStructures();
                    UnregisterWaitHandle();

                    throw new Win32Exception(error);
                }
            }

            return(tcs.Task);
        }
Exemple #58
0
 /// <summary>
 /// 尝试用指定的数据缓冲区以异步方式将 Internet 控制消息协议 (ICMP) 回显消息发送到具有指定的 System.Net.IPAddress
 /// 的计算机,并从该计算机接收对应的 ICMP 回显回复消息。此重载允许您指定操作的超时值,并控制 ICMP 回显消息数据包的碎片和生存时间值。
 /// </summary>
 /// <param name="hostNameOrAddress">一个 System.String,它标识作为 ICMP 回送消息目标的计算机。为此参数指定的值可以是主机名,也可以是以字符串形式表示的 IP 地址。</param>
 /// <param name="times">Ping命令发送次数。</param>
 /// <param name="timeout">一个 System.Byte 数组,它包含要与 ICMP 回送消息一起发送并在 ICMP 回送应答消息中返回的数据。该数组包含的字节数不能超过 65,500个字节。</param>
 /// <param name="buffer">一个 System.Byte 数组,它包含要与 ICMP 回送消息一起发送并在 ICMP 回送应答消息中返回的数据。该数组包含的字节数不能超过 65,500个字节</param>
 /// <param name="options">一个 System.Net.NetworkInformation.PingOptions 对象,用于控制 ICMP 回显消息数据包的碎片和生存时间值。</param>
 /// <param name="userToken">一个对象,此对象将被传递给异步操作完成后所调用的方法。</param>
 public void SendAsync(String hostNameOrAddress, Int32 times, Int32 timeout, Byte[] buffer, PingOptions options, Object userToken)
 {
     lock (this)
     {
         if (m_Pinging != false)
         {
             throw new InvalidOperationException("The call of SendAsync is underway.");
         }
         m_Times     = times;
         m_UserToken = userToken;
         m_Replys.Clear();
         m_Ping.SendAsync(hostNameOrAddress, timeout, buffer, options, userToken);
     }
 }
Exemple #59
0
        private async Task <PingReply> SendPingAsyncCore(IPAddress address, byte[] buffer, int timeout, PingOptions options)
        {
            try
            {
                Task <PingReply> t = RawSocketPermissions.CanUseRawSockets(address.AddressFamily) ?
                                     SendIcmpEchoRequestOverRawSocketAsync(address, buffer, timeout, options) :
                                     SendWithPingUtilityAsync(address, buffer, timeout, options);

                PingReply reply = await t.ConfigureAwait(false);

                if (_canceled)
                {
                    throw new OperationCanceledException();
                }
                return(reply);
            }
            finally
            {
                Finish();
            }
        }
Exemple #60
0
        private async Task <PingReply> SendWithPingUtilityAsync(IPAddress address, byte[] buffer, int timeout, PingOptions options)
        {
            using (Process p = GetPingProcess(address, buffer, options))
            {
                var processCompletion = new TaskCompletionSource <bool>(TaskCreationOptions.RunContinuationsAsynchronously);
                p.EnableRaisingEvents = true;
                p.Exited += (s, e) => processCompletion.SetResult(true);
                p.Start();

                var  cts         = new CancellationTokenSource();
                Task timeoutTask = Task.Delay(timeout, cts.Token);
                Task finished    = await Task.WhenAny(processCompletion.Task, timeoutTask).ConfigureAwait(false);

                if (finished == timeoutTask && !p.HasExited)
                {
                    // Try to kill the ping process if it didn't return. If it is already in the process of exiting,
                    // a Win32Exception will be thrown.
                    try
                    {
                        p.Kill();
                    }
                    catch (Win32Exception) { }
                    return(CreateTimedOutPingReply());
                }
                else
                {
                    cts.Cancel();
                    if (p.ExitCode == 1 || p.ExitCode == 2)
                    {
                        // Throw timeout for known failure return codes from ping functions.
                        return(CreateTimedOutPingReply());
                    }

                    try
                    {
                        string output = await p.StandardOutput.ReadToEndAsync().ConfigureAwait(false);

                        return(ParsePingUtilityOutput(address, output));
                    }
                    catch (Exception)
                    {
                        // If the standard output cannot be successfully parsed, throw a generic PingException.
                        throw new PingException(SR.net_ping);
                    }
                }
            }
        }