Inheritance: System.ComponentModel.Component, IDisposable
Example #1
2
        public static void ListAllHosts(byte[] ipBase, Action<AddressStruct> itemCallback)
        {
            for (int b4 = 0; b4 <= 255; b4++)
            {
                var ip = ipBase[0] + "." + ipBase[1] + "." + ipBase[2] + "." + b4;

                var ping = new Ping();
                ping.PingCompleted += (o, e) =>
                {
                    if (e.Error == null && e.Reply.Status == IPStatus.Success)
                        if (itemCallback != null)
                        {
                            GetMacAddress(
                                e.Reply.Address,
                                (mac) =>
                                {
                                    itemCallback(new AddressStruct()
                                    {
                                        IPAddress = e.Reply.Address,
                                        MacAddress = mac
                                    });
                                });
                        }
                };
                ping.SendAsync(ip, null);
            }
        }
Example #2
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++;
        }
        public override bool DoValidate()
        {
            #if !NET_CORE
            Ping p = new Ping();//创建Ping对象p
            PingReply pr = p.Send("www.baidu.com", 30000);//向指定IP或者主机名的计算机发送ICMP协议的ping数据包

            if (pr != null && pr.Status == IPStatus.Success)//如果ping成功
            {
                return true;
            }

            #else
            HttpClient clinet = new HttpClient();
            IAsyncResult asyncResult = clinet.GetStringAsync("http://www.baidu.com");
            if (!asyncResult.AsyncWaitHandle.WaitOne(2000))
            {
                return false;
            }
            if (((Task<string>)asyncResult).Result.Contains("<title>百度一下,你就知道</title>"))
            {
                return true;
            }
            Thread.Sleep(100);
            #endif
            return false;
        }
        async private void PingButton_Click(object sender, EventArgs e)
        {
            List<string> urls = new List<string>()
            {
                "www.habitat-spokane.org",
                "www.partnersintl.org",
                "www.iassist.org",
                "www.fh.org",
                "www.worldvision.org"
            };

            IPStatus status;

            Func<string, Task<IPStatus>> func =
                    async (localUrl) =>
                    {
                        Random random = new Random();
                        Ping ping = new Ping();
                        PingReply pingReply =
                            await ping.SendPingAsync(localUrl);
                        return pingReply.Status;
                    };

            StatusLabel.Text = "Pinging…";

            foreach(string url in urls)
            {
                status = await func(url);
                StatusLabel.Text +=
                    $@"{ Environment.NewLine 
                    }{ url }: { status.ToString() } ({
                    Thread.CurrentThread.ManagedThreadId 
                    })";
            }
        }
Example #5
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;
            }
        }
Example #6
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);
         }
     }
 }
Example #7
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;
        }
Example #8
0
        static void Main(string[] args)
        {
            // Set up a new variable that pings.
            var ping = new Ping(); 

            // Asks the user what website they want to ping.
            Console.WriteLine("What website do you want to check? Example(www.google.co.uk)");
            // Records their input.
            var website = Console.ReadLine();
            // Records the result of the ping.
            var result = ping.Send(website);
            // Set up an if else statement for if it fails or not.
            if (result.Status != IPStatus.Success)
            {
                // If fails website is down.
                Console.WriteLine("Website is Down.");
            } else
            {
                // If anything else i.e suceeds prints it is up.
                Console.WriteLine("Website is Up.");
            }

            // Stops program from terminating.
            Console.ReadLine();
        }
		public MainWindow()
		{
			InitializeComponent();

			ping = new Ping();

			ni = new System.Windows.Forms.NotifyIcon();
			ni.Icon = System.Drawing.Icon.FromHandle(Properties.Resources.plug.GetHicon());
			ni.Visible = true;
			ni.DoubleClick += delegate (object sender, EventArgs args)
			{
				this.Show();
				this.WindowState = WindowState.Normal;
			};

			intervalTextBox.Text = Properties.Settings.Default.interval;
			address1TextBox.Text = Properties.Settings.Default.addy1;
			address2TextBox.Text = Properties.Settings.Default.addy2;
			address3TextBox.Text = Properties.Settings.Default.addy3;
			statusLabel.Content = "";
			address1ResLabel.Content = "";
			address2ResLabel.Content = "";
			address3ResLabel.Content = "";

			timer = new DispatcherTimer();
			timer.Tick += new EventHandler(TimedEvent);
		}
Example #10
0
 /// <summary>
 /// Performs a pathping
 /// </summary>
 /// <param name="ipaTarget">The target</param>
 /// <param name="iHopcount">The maximum hopcount</param>
 /// <param name="iTimeout">The timeout for each ping</param>
 /// <returns>An array of PingReplys for the whole path</returns>
 public static PingReply[] PerformPathping(IPAddress ipaTarget, int iHopcount, int iTimeout)
 {
     System.Collections.ArrayList arlPingReply = new System.Collections.ArrayList();
     Ping myPing = new Ping();
     PingReply prResult = null;
     int iTimeOutCnt = 0;
     for (int iC1 = 1; iC1 < iHopcount && iTimeOutCnt<5; iC1++)
     {
         prResult = myPing.Send(ipaTarget, iTimeout, new byte[10], new PingOptions(iC1, false));
         if (prResult.Status == IPStatus.Success)
         {
             iC1 = iHopcount;
             iTimeOutCnt = 0;
         }
         else if (prResult.Status == IPStatus.TtlExpired)
         {
             iTimeOutCnt = 0;
         }
         else if (prResult.Status == IPStatus.TimedOut)
         {
             iTimeOutCnt++;
         }
         arlPingReply.Add(prResult);
     }
     PingReply[] prReturnValue = new PingReply[arlPingReply.Count];
     for (int iC1 = 0; iC1 < arlPingReply.Count; iC1++)
     {
         prReturnValue[iC1] = (PingReply)arlPingReply[iC1];
     }
     return prReturnValue;
 }
Example #11
0
 //    检查网络连接的函数
 public void checkNet()
 {
     Ping p = new Ping();//创建Ping对象p
     PingReply pr = p.Send(_Sip);//向指定IP或者主机名的计算机发送ICMP协议的ping数据包
     if (pr.Status == IPStatus.Success)//如果ping成功
     {
         Console.WriteLine("网络连接成功, 执行下面任务...");
         netIsOk = true;
     }
     else
     {
         int times = 0;//重新连接次数;
         do
         {
             if (times >= 1)
             {
                 MessageBox.Show("重新尝试连接超过12次,连接失败程序结束");
                 netIsOk = false;
                 return;
             }
             //  Thread.Sleep(5000);//等待十分钟(方便测试的话,你可以改为1000)
             pr = p.Send(_Sip);
             Console.WriteLine(pr.Status);
             times++;
         }
         while (pr.Status != IPStatus.Success);
          MessageBox.Show("连接成功");
         netIsOk = true;
         times = 0;//连接成功,重新连接次数清为0;
     }
 }
Example #12
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); //Чтение нажатия клавиши.
        }
Example #13
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;
        }
Example #14
0
        /// <summary>
        /// 线程创建时调用此方法来搜索局域网主机
        /// </summary>
        private void searchMethod()
        {
            lock (obj)
            {
                //因为是刷新列表,所以要先清空
                if (result != null)
                {
                    result.Clear();
                }

                try
                {
                    //扫描整个网段
                    for (int i = 1; i < 256; i++)
                    {
                        //ping主机从而获取其IP地址和主机名
                        Ping myPing = new Ping();
                        myPing.PingCompleted += new PingCompletedEventHandler(_myPing_PingCompleted);

                        //如果路由器不是这么设置的这个地方就要改~~~偷个懒~^_^
                        string pingIP = "10.0.2." + i.ToString();

                        //异步ping,防止主界面过长时间不响应
                        myPing.SendAsync(pingIP, null);
                        Thread.Sleep(1);
                    }
                }
                catch (Exception exp)
                {
                    MessageBox.Show("错误!");
                }
            }
        }
Example #15
0
        public void pingHost(string hostName, int pingCount)
        {
            if (pingCount == 0)
            {
                pingCount = 43200;
            }
            Console.WriteLine("Host, Response Time, Status, Time ");
            String fileName = String.Format(@"tping-{0}-{1}-{2}-{3}.csv", DateTime.Now.Day, DateTime.Now.Hour, DateTime.Now.Minute, DateTime.Now.Second);
            for (int i = 0; i < pingCount; i++)
            {
                Ping ping = new Ping();
                StreamWriter processedData = new StreamWriter(@fileName, true);
                try
                {
                    PingReply pingReply = ping.Send(hostName);

                    processedData.WriteLine("{0}, " + "{1}, " + "{2}, " + DateTime.Now.TimeOfDay, hostName, pingReply.RoundtripTime, pingReply.Status);
                    processedData.Close();
                    Console.WriteLine("{0}, " + "{1}, " + "{2}, " + DateTime.Now.TimeOfDay, hostName, pingReply.RoundtripTime, pingReply.Status);

                }
                catch (System.Net.NetworkInformation.PingException)
                {
                    processedData.WriteLine("{0}, " + "{1}, " + "{2}, " + DateTime.Now.TimeOfDay, hostName, 0, "Network Error");
                    Console.WriteLine("{0}, " + "{1}, " + "{2}, " + DateTime.Now.TimeOfDay, hostName, 0, "Network Error");
                    processedData.Close();
                    //Console.WriteLine(Ex);
                    //Environment.Exit(0);
                }
                Thread.Sleep(2000);
            }
            Console.WriteLine("\n" + "tping complete - {0} pings logged in {1}", pingCount, fileName);
        }
Example #16
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;
 }
Example #17
0
        /// <summary>
        /// Will use CheckOrResolveIpAddress() to get an IP Address, then try to ping it.
        /// </summary>
        /// <param name="toPing">The IP Address or Hostname to ping</param>
        /// <returns>Null if successful. The error message if an error occurred.</returns>
        private static string Ping(string toPing)
        {
            IPAddress ipAddress = CheckOrResolveIpAddress(toPing);

            if (ipAddress == null)
                return "Invalid IP Address/Hostname";

            Ping ping = new Ping();
            PingReply reply;

            try
            {
                reply = ping.Send(ipAddress);
            }
            catch (PingException pe)
            {
                return string.Format("Could not ping {0}, {1}", toPing, pe.Message);
            }
            catch (Exception e)
            {
                return string.Format("Could not ping {0}, {1}", toPing, e.Message);
            }

            if (reply != null && reply.Status == IPStatus.Success)
            {
                //string message = reply.Status.ToString();
                return null;
            }
            return string.Format("Could not ping {0}", toPing);
        }
Example #18
0
 public bool StartConnect(string IP, int TcpPort, int CtrlPort)
 {
     var ping = new Ping();
     if (ping.Send(IP).Status != IPStatus.Success)
     {
         Console.Write("サーバーがPINGに応答しません。接続しますか?\n10秒でキャンセルされます。(y/n):");
         string Res = new Reader().ReadLine(10000);
         if (Res == null || !Res.ToLower().StartsWith("y"))
             return false;
     }
     CommonManager.Instance.NWMode = true;
     if (!CommonManager.Instance.NW.ConnectServer(IP, (uint)CtrlPort
         , (uint)TcpPort, OutsideCmdCallback, this)) return false;
     byte[] binData;
     if (CommonManager.Instance.CtrlCmd.SendFileCopy("ChSet5.txt", out binData) == 1)
     {
         string filePath = @".\Setting";
         Directory.CreateDirectory(filePath);
         filePath += @"\ChSet5.txt";
         using (BinaryWriter w = new BinaryWriter(File.Create(filePath)))
         {
             w.Write(binData);
             w.Close();
         }
         ChSet5.LoadFile();
         return true;
     }
     return false;
 }
        public RemoteEnvironment(string ipAddress, string userName, string password, string psExecPath)
        {
            IpAddress = ipAddress;
              UserName = userName;
              Password = password;
            _psExecPath = psExecPath;

            // wait for ping
              RetryUtility.RetryAction(() =>
            {
              var ping = new Ping();
              var reply = ping.Send(IpAddress);
              OsTestLogger.WriteLine(string.Format("Pinging ip:{0}, reply: {1}", ipAddress, reply.Status));
              if (reply.Status != IPStatus.Success)
            throw new InvalidOperationException(string.Format("Remote IP {0} ping returns {1}", ipAddress, reply.Status));
            }, 50, 5000);

              // give time for the RPC service to start
              RetryUtility.RetryAction(() => { WmiWrapperInstance = new WmiWrapper(ipAddress, userName, password); }, 10, 5000);
              WindowsShellInstance = new WindowsShell(this, psExecPath);
              //this will populate the GuestEnvironmentVariables. Short time after start APPDATA may be empty
              RetryUtility.RetryAction( InvalidateCachedGuestEnvironmentVariables, 10, 10000);

              IsUACEnabled = CheckIsUAC();
        }
Example #20
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);
            }
        }
Example #21
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();
 }
        public bool CanPing(string address)
        {
            Ping ping = new Ping();

            try
            {
                PingReply reply = ping.Send(address);
                if (reply == null) return false;

                if (reply.Status == IPStatus.Success)
                {
                    this.Log.Debug("On-Line!");
                    return true;
                }
                else
                {
                    this.Log.Debug("Off-Line");
                    return false;
                }
            }
            catch (PingException)
            {
                this.Log.Debug("Off-Line");
                return false;
            }
        }
Example #23
0
        public static bool IsHostAccessible(string hostNameOrAddress)
        {
            if (String.IsNullOrEmpty(hostNameOrAddress))
                return false;
            using (var ping = new Ping())
            {
                PingReply reply;
                try
                {
                    reply = ping.Send(hostNameOrAddress, PingTimeout);
                }
                catch (Exception ex)
                {
                    if (ex is ArgumentNullException ||
                        ex is ArgumentOutOfRangeException ||
                        ex is InvalidOperationException ||
                        ex is SocketException )
                    {

                        return false;
                    }
                    throw;
                }
                if (reply != null) return reply.Status == IPStatus.Success;
            }
            return false;
        }
Example #24
0
        private void pingBaidu()
        {
            try
            {

                Ping p = new Ping();
                PingReply pr = p.Send("www.baidu.com");
                if (pr.Status == IPStatus.Success||true)
                {
                    MainWindow mw = new MainWindow();
                    mw.Show();
                    this.Close();
                }
                else
                {
                    MessageBox.Show("本程序需要网络连接,请先配置好当前网络环境");
                    return;
                }
            }
            catch (Exception)
            {
                MessageBox.Show("本程序需要网络连接,请先配置好当前网络环境");
                return;
            }
        }
        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));
            }
        }
Example #26
0
        protected override void Loop(CancellationToken token)
        {
            _isConnected = false;

            while (token.IsCancellationRequested == false)
            {
                bool isNetworkAvailable = NetworkInterface.GetIsNetworkAvailable();
                if (isNetworkAvailable)
                {
                    NetworkInterface[] ifs = NetworkInterface.GetAllNetworkInterfaces();
                    foreach (NetworkInterface @if in ifs)
                    {
                        // check for wireless and up
                        if (@if.NetworkInterfaceType == NetworkInterfaceType.Wireless80211 && @if.OperationalStatus == OperationalStatus.Up)
                        {
                            var ping = new Ping();
                            PingReply result = ping.Send(_config.Hostname);
                            if (result != null && result.Status == IPStatus.Success)
                            {
                                _isConnected = true;
                                _connectionChanged(true);
                            }
                            else
                            {
                                // todo add timeout?
                                _isConnected = false;
                                _connectionChanged(false);
                            }
                        }
                    }
                }
                Thread.Sleep(1000);
            }
        }
Example #27
0
        static void Main(string[] args)
        {
            var options = new argsParser();
            CommandLine.Parser.Default.ParseArguments(args, options);
            if (args.Length > 0)
            {
                var test = Uri.CheckHostName(options.ip);
                if (Uri.CheckHostName(options.ip) != UriHostNameType.Unknown)
                {
                    Ping ping = new Ping();
                    try
                    {
                        PingReply pingReply = ping.Send(options.ip);
                    }
                    catch
                    {
                        Console.WriteLine("Network Error: Please check network or hostname|ip");
                        Environment.Exit(0);
                    }
                    helper ping1 = new helper();
                    ping1.pingHost(options.ip, options.count);

                }
                else
                {
                    Console.WriteLine("Please enter a valid hostname or IP");
                }

            }
            else
            {
                Console.WriteLine("tping.exe -i [IP|Hostname] -c [Number of pings (Default is 43200)]");
            }
        }
Example #28
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;
        }
Example #29
0
        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");
        }
Example #30
0
    /// <summary>
    /// This function will deal with delays of setting up an agent.
    /// </summary>
    /// <returns>IEnumerator to allow for delays.</returns>
    public IEnumerator SlowAgentStart()
    {
        bool UsePublic  = false;
        bool UseFlorida = false;

        //Ping Public Ip address to see if we are external..........
        //GenericNetworkCore.Logger("Trying Public IP Address: " + PublicIP.ToString());
        System.Net.NetworkInformation.Ping        ping = new System.Net.NetworkInformation.Ping();
        System.Net.NetworkInformation.PingOptions po   = new System.Net.NetworkInformation.PingOptions();
        po.DontFragment = true;
        string data = "HELLLLOOOOO!";

        byte[] buffer  = ASCIIEncoding.ASCII.GetBytes(data);
        int    timeout = 500;

        System.Net.NetworkInformation.PingReply pr = ping.Send(PublicIP, timeout, buffer, po);
        yield return(new WaitForSeconds(1.5f));

        Debug.Log("Ping Return: " + pr.Status.ToString());
        if (pr.Status == System.Net.NetworkInformation.IPStatus.Success)
        {
            GenericNetworkCore.Logger("The public IP responded with a roundtrip time of: " + pr.RoundtripTime);
            UsePublic = true;
            IP        = PublicIP;
        }
        else
        {
            GenericNetworkCore.Logger("The public IP failed to respond");
            UsePublic = false;
        }
        //-------------------If not public, ping Florida Poly for internal access.
        if (!UsePublic)
        {
            GenericNetworkCore.Logger("Trying Florida Poly Address: " + FloridaPolyIP.ToString());
            pr = ping.Send(FloridaPolyIP, timeout, buffer, po);
            yield return(new WaitForSeconds(1.5f));

            Debug.Log("Ping Return: " + pr.Status.ToString());
            if (pr.Status.ToString() == "Success")
            {
                GenericNetworkCore.Logger("The Florida Poly IP responded with a roundtrip time of: " + pr.RoundtripTime);
                UseFlorida = true;
                IP         = FloridaPolyIP;
            }
            else
            {
                GenericNetworkCore.Logger("The Florida Poly IP failed to respond");
                UseFlorida = false;
            }
        }
        //Otherwise use local host, assume testing.
        if (!UsePublic && !UseFlorida)
        {
            IP = "127.0.0.1";
            GenericNetworkCore.Logger("Using Home Address!");
        }
        this.StartAgent();
    }
Example #31
0
 public PN()
 {
     System.Net.NetworkInformation.Ping      ping      = new System.Net.NetworkInformation.Ping();
     System.Net.NetworkInformation.PingReply pingReply = ping.Send("192.168.9.200"); //адрес куда надо отправить
     Console.WriteLine(pingReply.RoundtripTime);                                     //время ответа
     Console.WriteLine(pingReply.Status);                                            //статус
     Console.WriteLine(pingReply.Address);                                           //IP
     // Console.ReadKey(true);
 }
    private bool Ping()
    {
        System.Net.NetworkInformation.Ping      pingSender = new System.Net.NetworkInformation.Ping();
        System.Net.NetworkInformation.PingReply reply;
        try
        {
            reply = pingSender.Send("Google.com");
        }
        catch (Exception) { return(false); }
        if (reply.Status == System.Net.NetworkInformation.IPStatus.Success)
        {
            return(true);
        }

        return(false);
    }
Example #33
0
    public static bool Ping(string hostNameOrAddress, int timeout, out Exception error)
    {
        var success = false;

        error = null;
        var sw = new System.Diagnostics.Stopwatch();

        sw.Start();
        System.Net.NetworkInformation.PingReply reply = null;
        Exception replyError = null;
        // Use proper threading, because other asynchronous classes
        // like "Tasks" have problems with Ping.
        var ts = new System.Threading.ThreadStart(delegate()
        {
            var ping = new System.Net.NetworkInformation.Ping();
            try
            {
                reply = ping.Send(hostNameOrAddress);
            }
            catch (Exception ex)
            {
                replyError = ex;
            }
            ping.Dispose();
        });
        var t = new System.Threading.Thread(ts);

        t.Start();
        t.Join(timeout);
        if (reply != null)
        {
            success = (reply.Status == System.Net.NetworkInformation.IPStatus.Success);
        }
        else if (replyError != null)
        {
            error = replyError;
        }
        else
        {
            error = new Exception("Ping timed out (" + timeout.ToString() + "): " + sw.Elapsed.ToString());
        }
        return(success);
    }
Example #34
0
 private bool CheckImOnline()
 {
     if (_device._bd.VirtualDevice != null)
     {
         return(_device._bd.VirtualDevice.IsOnline);
     }
     try
     {
         var r1 = new System.Net.NetworkInformation.Ping().Send("www.google.com.mx").Status == System.Net.NetworkInformation.IPStatus.Success;
         var r2 = new System.Net.NetworkInformation.Ping().Send("www.bing.com").Status == System.Net.NetworkInformation.IPStatus.Success;
         return(r1 || r2);
     }
     catch (Exception ex)
     {
         System.Diagnostics.Debug.Print(ex.Message);
         System.Diagnostics.Debugger.Break();
     }
     return(false);
 }
Example #35
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);
        }
    }
Example #36
0
        static void Main(string[] args)
        {
            string           komuta   = "ipconfig /flushdns";
            Process          Process1 = new Process();
            ProcessStartInfo ProcessInfo1;

            ProcessInfo1 = new ProcessStartInfo("cmd.exe", "/C " + komuta);
            ProcessInfo1.CreateNoWindow  = true;
            ProcessInfo1.UseShellExecute = false;

            Process1 = Process.Start(ProcessInfo1);
            Process1.WaitForExit();
            Process1.Close();
            System.Net.NetworkInformation.Ping png = new System.Net.NetworkInformation.Ping();
            List <string> domain_list = new List <string>();
            int           sayi        = 1;

KontrolSubSayisi:
            try
            {
                Console.WriteLine("Subdomain sayısı:");
                string sayi_string = Console.ReadLine();
                Console.WriteLine("--------------------------------------------------------------------");
                sayi = Int32.Parse(sayi_string);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Sayı giriniz:" + ex.Message);
                goto KontrolSubSayisi;
            }
            for (int i = 0; i < sayi; i++)
            {
                Console.WriteLine("Domain adı:");
                string site = Console.ReadLine();
                domain_list.Add(site);
            }
            Console.WriteLine("--------------------------------------------------------------------");
KontrolDosyaAdi:
            string dosyaAdi;

            Console.WriteLine("Dosya adi giriniz:");
            dosyaAdi = Console.ReadLine();
            if (dosyaAdi == "")
            {
                Console.WriteLine("Boş geçmeyiniz");
                goto KontrolDosyaAdi;
            }
            Console.WriteLine("--------------------------------------------------------------------");
            Console.WriteLine("Test edilen kurumun adini giriniz");
            testEdilenKurum = Console.ReadLine();
            string timeout;

            Console.WriteLine("--------------------------------------------------------------------");
            Console.WriteLine("TimeOut' milisaniye cinsinden giriniz:");
            timeout = Console.ReadLine();
            TimeOut = Convert.ToInt32(timeout);
            Console.WriteLine("--------------------------------------------------------------------");
idKontrol:
            Console.WriteLine("Kendinize özel sayı ve karakterden oluşan 3 haneli anahtar tanımlayın");
            kullaniciID = Console.ReadLine();
            if (kullaniciID.Length != 3)
            {
                Console.WriteLine("Hatalı anahtar boyutu");
                goto idKontrol;
            }

            string islem_No;

            Console.WriteLine("--------------------------------------------------------------------");
Kontrol:
            Console.WriteLine("Dosyayı nasıl kaçırmak istediğinizi seçiniz");

            Console.WriteLine("1.)Byte");
            Console.WriteLine("2.)Base64");
            Console.WriteLine("3.)Base32");
            islem_No = Console.ReadLine();
            if (islem_No == "")
            {
                Console.WriteLine("Hatalı numara");
                goto Kontrol;
            }
            Console.WriteLine("--------------------------------------------------------------------");

            int Islem_No = Convert.ToInt32(islem_No);

            List <string> dizi        = new List <string>();
            List <string> veri_dizisi = new List <string>();
            string        yollanacak_veri;

            string[] dosyaAd = dosyaAdi.Split('\\');

            string newDosyaAdi = dosyaAd[dosyaAd.Count() - 1];

            if (Islem_No == 1)
            {
                string   y        = System.Convert.ToBase64String(GetBytes(testEdilenKurum));
                string[] kurum    = Regex.Split(y, "=");
                string   dosya    = System.Convert.ToBase64String(GetBytes(newDosyaAdi));
                string[] dosyaNew = Regex.Split(dosya, "=");

                dizi.Add(kurum[0]);
                dizi.Add(dosyaNew[0]);
                dizi.Add(islem_No);
                try
                {
                    byte[] content = File.ReadAllBytes(dosyaAdi);

                    string       result1 = System.Convert.ToBase64String(content);
                    StreamWriter a       = new StreamWriter("okan.txt");
                    a.WriteLine(result1);
                    a.Close();
                    byte[] content2 = File.ReadAllBytes(@"okan.txt");
                    string result = GetString(content2);
                    int    diziBoyutu = result.Length - 1, index = 0;
                    int    sayac = result.Length;


                    int kalan;
                    while (sayac > 16)
                    {
                        sayac -= 16;
                        dizi.Add(result.Substring(index, 16));
                        index += 16;
                    }
                    kalan = sayac;
                    dizi.Add(result.Substring(index, kalan));
                    string son = "bitti";

                    dizi.Add(son);
                    for (int i = 0; i < dizi.Count; i++)
                    {
                        yollanacak_veri = i + kullaniciID + "-" + dizi[i] + "." + domain_list[i % (domain_list.Count)];
                        veri_dizisi.Add(yollanacak_veri);
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine("Hatalı dosya adi:" + ex.Message);
                    goto KontrolDosyaAdi;
                }
            }
            else if (Islem_No == 2)
            {
                string   y        = System.Convert.ToBase64String(GetBytes(testEdilenKurum));
                string[] kurum    = Regex.Split(y, "=");
                string   dosya    = System.Convert.ToBase64String(GetBytes(newDosyaAdi));
                string[] dosyaNew = Regex.Split(dosya, "=");

                dizi.Add(kurum[0]);
                dizi.Add(dosyaNew[0]);
                dizi.Add(islem_No);
                try
                {
                    byte[] content = File.ReadAllBytes(dosyaAdi);

                    string result = System.Convert.ToBase64String(content);
                    result = result.Replace("/", "bolu");
                    result = result.Replace("+", "arti");
                    int    diziBoyutu = result.Length - 1, index = 0;
                    int    sayac  = result.Length;
                    Random random = new Random();
                    int    boyut  = random.Next(30, 52);

                    int kalan;
                    while (sayac > boyut)
                    {
                        boyut  = random.Next(30, 52);
                        sayac -= boyut;
                        dizi.Add(result.Substring(index, boyut));
                        index += boyut;
                    }
                    kalan = sayac;
                    string   y3 = result.Substring(index, kalan);
                    string[] ya = Regex.Split(y3, "=");
                    dizi.Add(ya[0]);
                    string son = "bitti";

                    dizi.Add(son);
                    for (int i = 0; i < dizi.Count; i++)
                    {
                        yollanacak_veri = i + kullaniciID + "-" + dizi[i] + "." + domain_list[i % (domain_list.Count)];
                        veri_dizisi.Add(yollanacak_veri);
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine("Hatalı dosya adi:" + ex.Message);
                    goto KontrolDosyaAdi;
                }
            }
            else if (Islem_No == 3)
            {
                string   y        = ToBase32String(GetBytes(testEdilenKurum));
                string[] kurum    = Regex.Split(y, "=");
                string   dosya    = ToBase32String(GetBytes(newDosyaAdi));
                string[] dosyaNew = Regex.Split(dosya, "=");

                dizi.Add(kurum[0]);
                dizi.Add(dosyaNew[0]);

                dizi.Add(islem_No);
                try
                {
                    byte[] content = File.ReadAllBytes(dosyaAdi);

                    string result = ToBase32String(content);
                    result = result.Replace("/", "bolu");
                    result = result.Replace("+", "arti");
                    int    diziBoyutu = result.Length - 1, index = 0;
                    int    sayac  = result.Length;
                    Random random = new Random();
                    int    boyut  = random.Next(30, 52);

                    int kalan;
                    while (sayac > boyut)
                    {
                        boyut  = random.Next(30, 52);
                        sayac -= boyut;
                        dizi.Add(result.Substring(index, boyut));
                        index += boyut;
                    }
                    kalan = sayac;
                    string   y2 = result.Substring(index, kalan);
                    string[] ya = Regex.Split(y2, "=");
                    dizi.Add(ya[0]);
                    string son = "bitti";

                    dizi.Add(son);
                    for (int i = 0; i < dizi.Count; i++)
                    {
                        yollanacak_veri = i + kullaniciID + "-" + dizi[i] + "." + domain_list[i % (domain_list.Count)];
                        veri_dizisi.Add(yollanacak_veri);
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine("Hatalı dosya adi:" + ex.Message);
                    goto KontrolDosyaAdi;
                }
            }
            else
            {
                Console.WriteLine("Hatalı işlem numarası tekrar seçiniz");
                goto Kontrol;
            }



            IPAddress[] ip;


            for (int i = 0; i < veri_dizisi.Count; i++)
            {
                System.Threading.Thread.Sleep(TimeOut);
                for (int j = 0; j < 2; j++)
                {
                    System.Threading.Thread.Sleep(TimeOut);
                    Ping ping = new Ping();
                    try
                    {
                        string           komut   = "ipconfig /flushdns";
                        Process          Process = new Process();
                        ProcessStartInfo ProcessInfo;
                        ProcessInfo = new ProcessStartInfo("cmd.exe", "/C " + komut);
                        ProcessInfo.CreateNoWindow  = true;
                        ProcessInfo.UseShellExecute = false;

                        Process = Process.Start(ProcessInfo);
                        Process.WaitForExit();
                        Process.Close();


                        IPHostEntry dns_bilgi = Dns.GetHostEntry(veri_dizisi[i]);

                        ip = dns_bilgi.AddressList;
                        foreach (IPAddress ipp in ip)
                        {
                            Console.WriteLine("adres:" + veri_dizisi[i] + " ip:" + ipp);
                        }

                        //PingReply DonenCevap = ping.Send(veri_dizisi[i]);
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine("adres:" + veri_dizisi[i] + " böyle bir adres yok");
                    }
                }
            }



            Console.ReadLine();
        }
Example #37
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);
        }
Example #38
0
        private void getVpnAsync()
        {
            BackgroundWorker bw = new BackgroundWorker();

            bw.RunWorkerCompleted +=
                delegate
            {
                LoadingAnim(false);
                ChangeVpn(VpnList._VpnList.First());

                foreach (Vpn_ vpn in VpnList._VpnList)
                {
                    ServerItem serverItem = new ServerItem();
                    serverItem.NameOf.Content = vpn.Country;
                    BitmapImage bitmapImage = new BitmapImage();
                    flags.TryGetValue(vpn.Country, out bitmapImage);
                    serverItem.Flag.Source = bitmapImage;
                    serverItem.vpn         = vpn;
                    long             repl = 0;
                    BackgroundWorker bw2  = new BackgroundWorker();
                    bw2.RunWorkerCompleted +=
                        delegate
                    {
                        if (repl > 120)
                        {
                            Brush brush = Brushes.Red;

                            serverItem.Ping.Foreground = brush;
                        }
                        if (repl < 120 & repl > 80)
                        {
                            Brush brush = Brushes.Yellow;

                            serverItem.Ping.Foreground = brush;
                        }
                        if (repl < 80)
                        {
                            Brush brush = Brushes.LimeGreen;

                            serverItem.Ping.Foreground = brush;
                        }
                        serverItem.Ping.Content = repl;
                        if (repl > 0)
                        {
                            serverItem.PreviewMouseDown +=
                                delegate
                            {
                                setSerstatus(false);
                                ChangeVpn(serverItem.vpn);
                            };
                            StackServers.Children.Add(serverItem);
                        }
                    };
                    bw2.DoWork +=
                        delegate
                    {
                        Ping      ping      = new System.Net.NetworkInformation.Ping();
                        PingReply pingReply = null;
                        pingReply = ping.Send(vpn.IP);

                        repl = pingReply.RoundtripTime / 2;
                    };
                    bw2.RunWorkerAsync();
                }
            };


            bw.DoWork +=
                delegate
            {
                for (int i = 0; i < 7; i++)
                {
                    try
                    {
                        string st = new WebClient()
                        {
                            Proxy = null
                        }.DownloadString(VpnServers[i][0]);
                        st = st.Remove(st.IndexOf("<h3>L2TP/IPSec (PSK)</h3>"), st.Length - st.IndexOf("<h3>L2TP/IPSec (PSK)</h3>", 10));
                        st = st.Remove(0, st.IndexOf("<h3>PPTP</h3>"));
                        string[] s  = new string[3];
                        int      k2 = 0;
                        while (st.Contains("</b>"))
                        {
                            string k = st.Remove(0, st.IndexOf("</b>") + 5);
                            k     = k.Remove(k.IndexOf("</li>"), k.Length - k.IndexOf("</li>"));
                            st    = st.Remove(0, st.IndexOf("</li>") + 5);
                            s[k2] = k;
                            k2++;
                        }
                        Vpn_ vpn = new Vpn_
                        {
                            IP      = s[0],
                            User    = s[1],
                            Pass    = s[2],
                            Country = VpnServers[i][1]
                        };
                        VpnList._VpnList.Add(vpn);
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.ToString());
                    }
                }
            };
            bw.RunWorkerAsync();
        }
        public void ScanAsync(IPAddress[] ipAddresses, IPScannerOptions ipScannerOptions, CancellationToken cancellationToken)
        {
            progressValue = 0;

            // Modify the ThreadPool for better performance
            ThreadPool.GetMinThreads(out int workerThreads, out int completionPortThreads);
            ThreadPool.SetMinThreads(workerThreads + ipScannerOptions.Threads, completionPortThreads + ipScannerOptions.Threads);

            // Start the scan in a separat task
            Task.Run(() =>
            {
                try
                {
                    ParallelOptions parallelOptions = new ParallelOptions()
                    {
                        CancellationToken      = cancellationToken,
                        MaxDegreeOfParallelism = ipScannerOptions.Threads
                    };

                    string localHostname = ipScannerOptions.ResolveHostname ? Dns.GetHostName() : string.Empty;

                    Parallel.ForEach(ipAddresses, parallelOptions, ipAddress =>
                    {
                        using (System.Net.NetworkInformation.Ping ping = new System.Net.NetworkInformation.Ping())
                        {
                            for (int i = 0; i < ipScannerOptions.Attempts; i++)
                            {
                                try
                                {
                                    // PING
                                    PingReply pingReply = ping.Send(ipAddress, ipScannerOptions.Timeout, ipScannerOptions.Buffer);

                                    if (IPStatus.Success == pingReply.Status)
                                    {
                                        PingInfo pingInfo = new PingInfo(pingReply.Address, pingReply.Buffer.Count(), pingReply.RoundtripTime, pingReply.Options.Ttl, pingReply.Status);

                                        // DNS
                                        string hostname = string.Empty;

                                        if (ipScannerOptions.ResolveHostname)
                                        {
                                            if (pingInfo.Status == IPStatus.Success)
                                            {
                                                try
                                                {
                                                    hostname = Dns.GetHostEntry(ipAddress).HostName;
                                                }
                                                catch (SocketException) { } // Couldn't resolve hostname
                                            }
                                        }

                                        // ARP
                                        PhysicalAddress macAddress = null;
                                        string vendor = string.Empty;

                                        if (ipScannerOptions.ResolveMACAddress)
                                        {
                                            macAddress = ARPTable.GetTable().Where(p => p.IPAddress.ToString() == ipAddress.ToString()).FirstOrDefault().MACAddress;

                                            if (macAddress == null)
                                            {
                                                macAddress = NetworkInterface.GetNetworkInterfaces().Where(p => p.IPv4Address.Contains(ipAddress)).FirstOrDefault().PhysicalAddress;
                                            }

                                            // Vendor lookup
                                            vendor = OUILookup.Lookup(macAddress.ToString()).FirstOrDefault().Vendor;
                                        }

                                        OnHostFound(new IPScannerHostFoundArgs(pingInfo, hostname, macAddress, vendor));

                                        break;
                                    }
                                }
                                catch { }

                                // Don't scan again, if the user has canceled (when more than 1 attempt)
                                if (cancellationToken.IsCancellationRequested)
                                {
                                    break;
                                }
                            }
                        }

                        // Increase the progress
                        Interlocked.Increment(ref progressValue);
                        OnProgressChanged();
                    });

                    OnScanComplete();
                }
                catch (OperationCanceledException)  // If user has canceled
                {
                    OnUserHasCanceled();
                }
            });

            // Reset the ThreadPool to default
            ThreadPool.SetMinThreads(workerThreads, completionPortThreads);
        }
Example #40
0
 private void lookupToolStripMenuItem_Click(object sender, EventArgs e)
 {
     if (dataGridView1.SelectedCells.Count == 1)
     {
         DataGridViewCell   dc  = dataGridView1.SelectedCells[0];
         DataGridViewColumn dgc = dataGridView1.Columns[dc.ColumnIndex];
         if (dgc.Name.Equals("src-ip") || dgc.Name.Equals("dst-ip"))
         {
             string Ip = dc.Value.ToString();
             if (!Ip.StartsWith("192.168") && !Ip.StartsWith("255.") && !Ip.Equals("239.255.255.250"))
             {
                 System.Net.NetworkInformation.Ping ping = new System.Net.NetworkInformation.Ping();
                 ping.PingCompleted += (a, b) =>
                 {
                     MessageBox.Show(Ip + "\n" + b.Reply.Status.ToString());
                 };
                 IPAddress address;
                 if (IPAddress.TryParse(Ip, out address))
                 {
                     if (!iptrace.ContainsKey(address))
                     {
                         if (!iphost.ContainsKey(address))
                         {
                             try
                             {
                                 IPHostEntry iph = System.Net.Dns.EndGetHostEntry(System.Net.Dns.BeginGetHostEntry(address, (a) =>
                                 {
                                     if (a.IsCompleted)
                                     {
                                         string s = "";
                                     }
                                 }, null));
                                 iphost.Add(address, iph);
                                 AddToolTipTextToIp(address, iph);
                             }
                             catch { }
                         }
                         else
                         {
                             AddToolTipTextToIp(address, iphost[address]);
                         }
                         BackgroundWorker bw = new BackgroundWorker();
                         bw.DoWork += (a, b) =>
                         {
                             IPAddress ipaddress = (IPAddress)b.Argument;
                             TraceForm tf        = new TraceForm(ipaddress);
                             tf.Tag = Diag.PerformPathping(ipaddress, 50, 5000);
                             iptrace.Add(address, tf);
                             tf.ShowDialog();
                         };
                         bw.RunWorkerAsync(address);
                     }
                     else
                     {
                         iptrace[address].ShowDialog();
                     }
                 }
                 //ping.SendAsync(dc.Value.ToString(),null);
             }
         }
     }
 }
Example #41
0
        public void ScanAsync(IPAddress[] ipAddresses, CancellationToken cancellationToken)
        {
            // Start the scan in a separat task
            Task.Run(() =>
            {
                _progressValue = 0;

                // Create dns client and set options

                if (ResolveHostname)
                {
                    DnsLookupClient            = UseCustomDNSServer ? new LookupClient(new IPEndPoint(CustomDNSServer, CustomDNSPort)) : new LookupClient();
                    DnsLookupClient.UseCache   = DNSUseCache;
                    DnsLookupClient.Recursion  = DNSRecursion;
                    DnsLookupClient.Timeout    = DNSTimeout;
                    DnsLookupClient.Retries    = DNSRetries;
                    DnsLookupClient.UseTcpOnly = DNSUseTCPOnly;
                }

                // Modify the ThreadPool for better performance
                ThreadPool.GetMinThreads(out var workerThreads, out var completionPortThreads);
                ThreadPool.SetMinThreads(workerThreads + Threads, completionPortThreads + Threads);

                try
                {
                    var parallelOptions = new ParallelOptions
                    {
                        CancellationToken      = cancellationToken,
                        MaxDegreeOfParallelism = Threads
                    };

                    Parallel.ForEach(ipAddresses, parallelOptions, ipAddress =>
                    {
                        var pingInfo = new PingInfo();
                        var pingable = false;

                        // PING
                        using (var ping = new System.Net.NetworkInformation.Ping())
                        {
                            for (var i = 0; i < ICMPAttempts; i++)
                            {
                                try
                                {
                                    var pingReply = ping.Send(ipAddress, ICMPTimeout, ICMPBuffer);

                                    if (pingReply != null && IPStatus.Success == pingReply.Status)
                                    {
                                        pingInfo = new PingInfo(pingReply.Address, pingReply.Buffer.Length, pingReply.RoundtripTime, pingReply.Options.Ttl, pingReply.Status);

                                        pingable = true;
                                        break;  // Continue with the next checks...
                                    }

                                    if (pingReply != null)
                                    {
                                        pingInfo = new PingInfo(ipAddress, pingReply.Status);
                                    }
                                }
                                catch (PingException)
                                { }

                                // Don't scan again, if the user has canceled (when more than 1 attempt)
                                if (cancellationToken.IsCancellationRequested)
                                {
                                    break;
                                }
                            }
                        }

                        if (pingable || ShowScanResultForAllIPAddresses)
                        {
                            // DNS
                            var hostname = string.Empty;

                            if (ResolveHostname)
                            {
                                try
                                {
                                    var dnsQueryResponse = DnsLookupClient.QueryReverse(ipAddress);

                                    if (dnsQueryResponse != null && !dnsQueryResponse.HasError)
                                    {
                                        hostname = dnsQueryResponse.Answers.PtrRecords().FirstOrDefault()?.PtrDomainName;
                                    }
                                    else
                                    {
                                        hostname = DNSShowErrorMessage ? $"{Resources.Localization.Strings.Error}: {dnsQueryResponse.ErrorMessage}" : "";
                                    }
                                }
                                catch (Exception ex)
                                {
                                    hostname = DNSShowErrorMessage ? $"{Resources.Localization.Strings.Error}: {ex.Message}" : "";
                                }
                            }

                            // ARP
                            PhysicalAddress macAddress = null;
                            var vendor = string.Empty;

                            if (ResolveMACAddress)
                            {
                                // Get info from arp table
                                var arpTableInfo = ARP.GetTable().FirstOrDefault(p => p.IPAddress.ToString() == ipAddress.ToString());

                                if (arpTableInfo != null)
                                {
                                    macAddress = arpTableInfo.MACAddress;
                                }

                                // Check if it is the local mac
                                if (macAddress == null)
                                {
                                    var networkInferfaceInfo = NetworkInterface.GetNetworkInterfaces().FirstOrDefault(p => p.IPv4Address.Contains(ipAddress));

                                    if (networkInferfaceInfo != null)
                                    {
                                        macAddress = networkInferfaceInfo.PhysicalAddress;
                                    }
                                }

                                // Vendor lookup
                                if (macAddress != null)
                                {
                                    var info = OUILookup.Lookup(macAddress.ToString()).FirstOrDefault();

                                    if (info != null)
                                    {
                                        vendor = info.Vendor;
                                    }
                                }
                            }

                            OnHostFound(new HostFoundArgs(pingInfo, hostname, macAddress, vendor));
                        }

                        IncreaseProcess();
                    });


                    OnScanComplete();
                }
                catch (OperationCanceledException)  // If user has canceled
                {
                    // Check if the scan is already complete...
                    if (ipAddresses.Length == _progressValue)
                    {
                        OnScanComplete();
                    }
                    else
                    {
                        OnUserHasCanceled();
                    }
                }
                finally
                {
                    // Reset the ThreadPool to default
                    ThreadPool.GetMinThreads(out workerThreads, out completionPortThreads);
                    ThreadPool.SetMinThreads(workerThreads - Threads, completionPortThreads - Threads);
                }
            }, cancellationToken);
        }
Example #42
0
 public Ping(string host)
 {
     System.Net.NetworkInformation.Ping ping = new System.Net.NetworkInformation.Ping();
     pr = ping.Send(host);
 }
Example #43
0
        public void ScanAsync(IPAddress[] ipAddresses, IPScannerOptions ipScannerOptions, CancellationToken cancellationToken)
        {
            // Start the scan in a separat task
            Task.Run(() =>
            {
                progressValue = 0;

                // Modify the ThreadPool for better performance
                ThreadPool.GetMinThreads(out int workerThreads, out int completionPortThreads);
                ThreadPool.SetMinThreads(workerThreads + ipScannerOptions.Threads, completionPortThreads + ipScannerOptions.Threads);

                try
                {
                    ParallelOptions parallelOptions = new ParallelOptions()
                    {
                        CancellationToken      = cancellationToken,
                        MaxDegreeOfParallelism = ipScannerOptions.Threads
                    };

                    string localHostname = ipScannerOptions.ResolveHostname ? Dns.GetHostName() : string.Empty;

                    Parallel.ForEach(ipAddresses, parallelOptions, ipAddress =>
                    {
                        PingInfo pingInfo = new PingInfo();
                        bool pingable     = false;

                        // PING
                        using (System.Net.NetworkInformation.Ping ping = new System.Net.NetworkInformation.Ping())
                        {
                            for (int i = 0; i < ipScannerOptions.Attempts; i++)
                            {
                                try
                                {
                                    PingReply pingReply = ping.Send(ipAddress, ipScannerOptions.Timeout, ipScannerOptions.Buffer);

                                    if (IPStatus.Success == pingReply.Status)
                                    {
                                        pingInfo = new PingInfo(pingReply.Address, pingReply.Buffer.Count(), pingReply.RoundtripTime, pingReply.Options.Ttl, pingReply.Status);

                                        pingable = true;
                                        break; // Continue with the next checks...
                                    }
                                    else
                                    {
                                        pingInfo = new PingInfo(ipAddress, pingReply.Status);
                                    }
                                }
                                catch (PingException)
                                {
                                }

                                // Don't scan again, if the user has canceled (when more than 1 attempt)
                                if (cancellationToken.IsCancellationRequested)
                                {
                                    break;
                                }
                            }
                        }

                        if (pingable || ipScannerOptions.ShowScanResultForAllIPAddresses)
                        {
                            // DNS
                            string hostname = string.Empty;

                            if (ipScannerOptions.ResolveHostname)
                            {
                                try
                                {
                                    hostname = Dns.GetHostEntry(ipAddress).HostName;
                                }
                                catch (SocketException) { } // Couldn't resolve hostname
                            }

                            // ARP
                            PhysicalAddress macAddress = null;
                            string vendor = string.Empty;

                            if (ipScannerOptions.ResolveMACAddress)
                            {
                                // Get info from arp table
                                ARPTableInfo arpTableInfo = ARPTable.GetTable().Where(p => p.IPAddress.ToString() == ipAddress.ToString()).FirstOrDefault();

                                if (arpTableInfo != null)
                                {
                                    macAddress = arpTableInfo.MACAddress;
                                }

                                // Check if it is the local mac
                                if (macAddress == null)
                                {
                                    NetworkInterfaceInfo networkInferfaceInfo = NetworkInterface.GetNetworkInterfaces().Where(p => p.IPv4Address.Contains(ipAddress)).FirstOrDefault();

                                    if (networkInferfaceInfo != null)
                                    {
                                        macAddress = networkInferfaceInfo.PhysicalAddress;
                                    }
                                }

                                // Vendor lookup
                                if (macAddress != null)
                                {
                                    OUIInfo info = OUILookup.Lookup(macAddress.ToString()).FirstOrDefault();

                                    if (info != null)
                                    {
                                        vendor = info.Vendor;
                                    }
                                }
                            }

                            OnHostFound(new IPScannerHostFoundArgs(pingInfo, hostname, macAddress, vendor));
                        }

                        IncreaseProcess();
                    });

                    OnScanComplete();
                }
                catch (OperationCanceledException)  // If user has canceled
                {
                    // Check if the scan is already complete...
                    if (ipAddresses.Length == progressValue)
                    {
                        OnScanComplete();
                    }
                    else
                    {
                        OnUserHasCanceled();
                    }
                }
                finally
                {
                    // Reset the ThreadPool to default
                    ThreadPool.GetMinThreads(out workerThreads, out completionPortThreads);
                    ThreadPool.SetMinThreads(workerThreads - ipScannerOptions.Threads, completionPortThreads - ipScannerOptions.Threads);
                }
            });
        }
Example #44
0
 public long Ping()
 {
     System.Net.NetworkInformation.Ping      tempPing     = new System.Net.NetworkInformation.Ping();
     System.Net.NetworkInformation.PingReply temPingReply = tempPing.Send(m_ipAddr);
     return(temPingReply.RoundtripTime);
 }
Example #45
0
 public void Ping()
 {
     buffer  = Encoding.ASCII.GetBytes(data);
     options = new PingOptions();
     options.DontFragment = true;
     p     = new System.Net.NetworkInformation.Ping();
     reply = p.Send(IP, systemTimeOut, buffer);
     if (reply.Status == IPStatus.Unknown)
     {
         writeLine("未知原因,请检测网卡.code:Unknown");
     }
     else if (reply.Status == IPStatus.TimedOut)
     {
         writeLine("请求超时." + "回复时长:" + reply.RoundtripTime + "无应答code:TimedOut");
     }
     else if (reply.Status == IPStatus.BadDestination)
     {
         writeLine("坏的目标无法到达.code:BadDestination");
     }
     else if (reply.Status == IPStatus.BadRoute)
     {
         writeLine("路由无法到达.code:BadRoute");
     }
     else if (reply.Status == IPStatus.DestinationNetworkUnreachable)
     {
         writeLine("无法访问计算机网络.code:DestinationNetworkUnreachable");
     }
     else if (reply.Status == IPStatus.DestinationProhibited)
     {
         writeLine("目标被禁Ping.code:DestinationProhibited");
     }
     else if (reply.Status == IPStatus.DestinationScopeMismatch)
     {
         writeLine("目标地址与原地址不在同一网络.code:DestinationScopeMismatch");
     }
     else if (reply.Status == IPStatus.DestinationUnreachable)
     {
         writeLine("无法得知回复消息,原因未知.code:DestinationUnreachable");
     }
     else if (reply.Status == IPStatus.HardwareError)
     {
         writeLine("硬件错误.code:HardwareError");
     }
     else if (reply.Status == IPStatus.PacketTooBig)
     {
         writeLine("MTU达到最大.code:PacketTooBig");
     }
     else if (reply.Status == IPStatus.TtlExpired)
     {
         writeLine("路由值达到最大,未到达,TTl耗尽code:TtlExpired");
     }
     else
     {
         if (reply.RoundtripTime > timeout)
         {
             mgstemp = "回复时长:" + reply.RoundtripTime + "ms; 大于" + timeout + "ms,istimout,算超时.IP:" + reply.Address;
         }
         else
         {
             mgstemp = "回复时长:" + reply.RoundtripTime + "ms.IP:" + reply.Address;
         }
         writeLine(mgstemp);
     }
 }
Example #46
0
 public static Task <PingReply> SendPingAsync(this Ping self, string hostNameOrAddress, int timeout)
 {
     return(Task.Factory.StartNew(() => { return self.Send(hostNameOrAddress, timeout); }));
 }
Example #47
0
    public static async void InstantInfoEquip(HttpListenerContext ctx)
    {
        WebSocketContext wsc;
        WebSocket        ws;

        try {
            wsc = await ctx.AcceptWebSocketAsync(null);

            ws = wsc.WebSocket;
        } catch (WebSocketException ex) {
            ctx.Response.Close();
            Logging.Err(ex);
            return;
        }

        string sessionId = ctx.Request.Cookies["sessionid"]?.Value ?? null;

        if (sessionId is null)
        {
            ctx.Response.Close();
            return;
        }

        try {
            byte[] buff = new byte[2048];
            WebSocketReceiveResult receiveResult = await ws.ReceiveAsync(new ArraySegment <byte>(buff), CancellationToken.None);

            string filename = Encoding.Default.GetString(buff, 0, receiveResult.Count);
            if (!Database.equip.ContainsKey(filename))
            {
                await ws.CloseAsync(WebSocketCloseStatus.NormalClosure, "", CancellationToken.None);

                return;
            }

            Database.DbEntry equip = (Database.DbEntry)Database.equip[filename];

            string host = null;
            if (equip.hash.ContainsKey("IP"))
            {
                host = ((string[])equip.hash["IP"])[0];
            }
            else if (equip.hash.ContainsKey("HOSTNAME"))
            {
                host = ((string[])equip.hash["HOSTNAME"])[0];
            }
            else
            {
                await ws.CloseAsync(WebSocketCloseStatus.NormalClosure, "", CancellationToken.None);

                return;
            }

            string   lastseen = "";
            string[] ipArray  = host.Split(';').Select(o => o.Trim()).ToArray();

            try {
                using System.Net.NetworkInformation.Ping p = new System.Net.NetworkInformation.Ping();
                PingReply reply = p.Send(ipArray[0], 1000);

                if (reply.Status == IPStatus.Success)
                {
                    lastseen = "Just now";
                    WsWriteText(ws, $"last seen{(char)127}{lastseen}{(char)127}ICMP");
                    WsWriteText(ws, $".roundtrip:{ipArray[0]}{(char)127}{reply.RoundtripTime}{(char)127}ICMP");
                    LastSeen.Seen(ipArray[0]);
                }
                else
                {
                    lastseen = Encoding.UTF8.GetString(LastSeen.HasBeenSeen(ipArray[0], true));
                    WsWriteText(ws, $"last seen{(char)127}{lastseen}{(char)127}ICMP");
                    WsWriteText(ws, $".roundtrip:{ipArray[0]}{(char)127}TimedOut{(char)127}ICMP");
                }
            } catch {
                WsWriteText(ws, $".roundtrip:{host}{(char)127}Error{(char)127}ICMP");
            }

            if (ipArray.Length > 1)
            {
                for (int i = 1; i < ipArray.Length; i++)
                {
                    try {
                        using System.Net.NetworkInformation.Ping p = new System.Net.NetworkInformation.Ping();
                        PingReply reply = p.Send(ipArray[i], 1000);
                        if (reply.Status == IPStatus.Success)
                        {
                            WsWriteText(ws, $".roundtrip:{ipArray[i]}{(char)127}{reply.RoundtripTime}{(char)127}ICMP");
                        }
                        else
                        {
                            WsWriteText(ws, $".roundtrip:{ipArray[i]}{(char)127}{reply.Status}{(char)127}ICMP");
                        }
                    } catch {
                        WsWriteText(ws, $".roundtrip:{ipArray[i]}{(char)127}Error{(char)127}ICMP");
                    }
                }
            }


            List <string> warnings = new List <string>();
            string        wmiHostName = null, adHostName = null, netbios = null, dns = null;


            if (lastseen == "Just now")
            {
                ManagementScope scope = Wmi.WmiScope(host);
                if (scope != null)
                {
                    string username = Wmi.WmiGet(scope, "Win32_ComputerSystem", "UserName", false, null);
                    if (username.Length > 0)
                    {
                        WsWriteText(ws, $"logged in user{(char)127}{username}{(char)127}WMI");
                    }

                    string starttime = Wmi.WmiGet(scope, "Win32_LogonSession", "StartTime", false, new Wmi.FormatMethodPtr(Wmi.DateTimeToString));
                    if (starttime.Length > 0)
                    {
                        WsWriteText(ws, $"start time{(char)127}{starttime}{(char)127}WMI");
                    }

                    wmiHostName = Wmi.WmiGet(scope, "Win32_ComputerSystem", "DNSHostName", false, null);
                }

                using ManagementObjectCollection logicalDisk = new ManagementObjectSearcher(scope, new SelectQuery("SELECT * FROM Win32_LogicalDisk WHERE DriveType = 3")).Get();
                foreach (ManagementObject o in logicalDisk)
                {
                    string caption = o.GetPropertyValue("Caption").ToString();
                    UInt64 size    = (UInt64)o.GetPropertyValue("Size");
                    UInt64 free    = (UInt64)o.GetPropertyValue("FreeSpace");

                    if (size == 0)
                    {
                        continue;
                    }
                    UInt64 percent = 100 * free / size;

                    if (percent < 10)
                    {
                        warnings.Add($"{percent}% free space on disk {caption}");
                    }
                }
            }

            if (equip.hash.ContainsKey("HOSTNAME"))
            {
                string       hostname = ((string[])equip.hash["HOSTNAME"])[0];
                SearchResult result   = ActiveDirectory.GetWorkstation(hostname);

                if (result != null)
                {
                    if (result.Properties["lastLogonTimestamp"].Count > 0)
                    {
                        string time = ActiveDirectory.FileTimeString(result.Properties["lastLogonTimestamp"][0].ToString());
                        if (time.Length > 0)
                        {
                            WsWriteText(ws, $"last logon{(char)127}{time}{(char)127}Active directory");
                        }
                    }

                    if (result.Properties["lastLogoff"].Count > 0)
                    {
                        string time = ActiveDirectory.FileTimeString(result.Properties["lastLogoff"][0].ToString());
                        if (time.Length > 0)
                        {
                            WsWriteText(ws, $"last logoff{(char)127}{time}{(char)127}Active directory");
                        }
                    }

                    if (result.Properties["dNSHostName"].Count > 0)
                    {
                        adHostName = result.Properties["dNSHostName"][0].ToString();
                    }
                }
            }

            try {
                dns = (await System.Net.Dns.GetHostEntryAsync(host)).HostName;
            } catch { }

            if (!(dns is null))
            {
                dns = dns?.Split('.')[0].ToUpper();
                bool mismatch = false;

                if (!mismatch && !(wmiHostName is null) && wmiHostName.Length > 0)
                {
                    wmiHostName = wmiHostName?.Split('.')[0].ToUpper();
                    if (wmiHostName != dns)
                    {
                        warnings.Add($"DNS mismatch: {wmiHostName} &ne; {dns}");
                        mismatch = true;
                    }
                }

                if (!mismatch && !(adHostName is null) && adHostName.Length > 0)
                {
                    adHostName = adHostName?.Split('.')[0].ToUpper();
                    if (adHostName != dns)
                    {
                        warnings.Add($"DNS mismatch: {adHostName} &ne; {dns}");
                        mismatch = true;
                    }
                }

                if (!mismatch && wmiHostName is null && adHostName is null)
                {
                    netbios = await NetBios.GetBiosNameAsync(host);
                }

                if (!mismatch && !(netbios is null) && netbios.Length > 0)
                {
                    netbios = netbios?.Split('.')[0].ToUpper();
                    if (netbios != dns)
                    {
                        warnings.Add($"DNS mismatch: {netbios} &ne; {dns}");
                        mismatch = true;
                    }
                }
            }

            for (int i = 0; i < warnings.Count; i++)
            {
                WsWriteText(ws, $"!{(char)127}{warnings[i]}{(char)127}");
            }

            try {
                await ws.CloseAsync(WebSocketCloseStatus.NormalClosure, "", CancellationToken.None);
            } catch { }
        } catch (Exception ex) {
            Logging.Err(ex);
        }
    }
Example #48
0
        public void PingProcess(object sender, EventArgs e)
        {
            PingReply Reply;

            System.Net.NetworkInformation.Ping p = new System.Net.NetworkInformation.Ping();
            switch (MainWindow.PingDestination)
            {
            case "JP-Auth":

                Reply = p.Send("122.129.233.160");
                if (Reply.Status == IPStatus.Success)
                {
                    ping.Content = "Ping:" + Reply.RoundtripTime + "ms";
                }
                ping.Foreground = Brushes.Green;
                if (Reply.RoundtripTime >= 200)
                {
                    ping.Foreground = Brushes.Yellow;
                }
                if (Reply.RoundtripTime >= 300)
                {
                    ping.Foreground = Brushes.Red;
                }
                if (MainWindow.TimeSpanSec < 3)
                {
                    Message.PingingTimeSpan_NotAllowed();
                    mTimer.Stop();
                    mTimer.Interval        = TimeSpan.FromSeconds(3);
                    MainWindow.TimeSpanSec = 3;
                    //MessageBox.Show("Alert" + "TimeSpan:" + main.TimeSpanSec);
                    Util.WriteSettings();
                    mTimer.Start();
                }
                break;

            case "Taiwan-KR":

                Reply = p.Send("inven.co.kr");
                if (Reply.Status == IPStatus.Success)
                {
                    ping.Content = "Ping:" + Reply.RoundtripTime + "ms";
                }
                if (Reply.RoundtripTime <= 100)
                {
                    ping.Foreground = Brushes.GreenYellow;
                }
                if (Reply.RoundtripTime >= 100)
                {
                    ping.Foreground = Brushes.Yellow;
                }
                if (Reply.RoundtripTime >= 200)
                {
                    ping.Foreground = Brushes.Red;
                }
                if (MainWindow.TimeSpanSec < 3)
                {
                    Message.PingingTimeSpan_NotAllowed();
                    mTimer.Stop();
                    mTimer.Interval        = TimeSpan.FromSeconds(3);
                    MainWindow.TimeSpanSec = 2;
                    //MessageBox.Show("Alert" + "TimeSpan:" + main.TimeSpanSec);
                    Util.WriteSettings();
                    mTimer.Start();
                }
                break;

            case "JP-Tokyo":
                if (MainWindow.TimeSpanSec < 3)
                {
                    Message.PingingTimeSpan_NotAllowed();
                    mTimer.Stop();
                    mTimer.Interval        = TimeSpan.FromSeconds(3);
                    MainWindow.TimeSpanSec = 3;
                    //MessageBox.Show("Alert" + "TimeSpan:" + main.TimeSpanSec);
                    Util.WriteSettings();
                    mTimer.Start();
                }
                break;

            case "NA-Sanjose":
                if (MainWindow.TimeSpanSec < 3)
                {
                    Message.PingingTimeSpan_NotAllowed();
                    mTimer.Stop();
                    mTimer.Interval        = TimeSpan.FromSeconds(3);
                    MainWindow.TimeSpanSec = 3;
                    //MessageBox.Show("Alert" + "TimeSpan:" + main.TimeSpanSec);
                    Util.WriteSettings();
                    mTimer.Start();
                }
                break;

            case "GamezBD":
                Reply = p.Send("64.91.227.116");
                if (Reply.Status == IPStatus.Success)
                {
                    ping.Content = "Ping:" + Reply.RoundtripTime + "ms";
                }
                Server.Content    = "(Gamez BD)";
                Server.Foreground = Brushes.Aqua;
                ping.Foreground   = Brushes.Aqua;
                if (Reply.RoundtripTime <= 100)
                {
                    ping.Foreground = Brushes.Aqua;
                }
                if (Reply.RoundtripTime >= 200)
                {
                    ping.Foreground = Brushes.Yellow;
                }
                if (Reply.RoundtripTime >= 300)
                {
                    ping.Foreground = Brushes.Red;
                }
                break;
            }

            //if (main.Destination == "KR-Auth" && main.TimeSpanSec < 3)
            //{
            //    main.PingingTimeSpan_NotAllowed();
            //    mTimer.Stop();
            //    mTimer.Interval = TimeSpan.FromSeconds(3);
            //    main.TimeSpanSec = 3;

            //    conf.WriteTheSettingsToIni();
            //    mTimer.Start();

            //}
            //if (main.Destination == "JP-Tokyo")
            //{
            //    System.Net.NetworkInformation.Ping p = new System.Net.NetworkInformation.Ping();
            //    PingReply Reply = p.Send("133.130.113.6");
            //    if (Reply.Status == IPStatus.Success)
            //    {
            //        ping.Content = "Ping:" + Reply.RoundtripTime + "ms";
            //    }
            //}
            //if(main.Destination == "NA-Sanjose")
            //{
            //    System.Net.NetworkInformation.Ping p = new System.Net.NetworkInformation.Ping();
            //    PingReply Reply = p.Send("163.44.119.33");
            //    if (Reply.Status == IPStatus.Success)
            //    {
            //        ping.Content = "Ping:" + Reply.RoundtripTime + "ms";
            //    }
            //}
            //if(main.Destination == "JP-Auth")
            //{
            //    System.Net.NetworkInformation.Ping p = new System.Net.NetworkInformation.Ping();
            //    PingReply Reply = p.Send("122.129.233.160");
            //    if (Reply.Status == IPStatus.Success)
            //    {
            //        ping.Content = "Ping:" + Reply.RoundtripTime + "ms";
            //    }
            //}
            //if(main.Destination == "KR-Auth")
            //{
            //    System.Net.NetworkInformation.Ping p = new System.Net.NetworkInformation.Ping();
            //    PingReply Reply = p.Send("blackauth.black.game.daum.net");
            //    if (Reply.Status == IPStatus.Success)
            //    {
            //        ping.Content = "Ping:" + Reply.RoundtripTime + "ms";
            //    }

            //}
        }
Example #49
0
        /// <summary>
        /// 创建多个线程ping指定范围的ip
        /// </summary>
        private void StartPing()
        {
            if (int.Parse(textBox2.Text) > 255 || int.Parse(textBox2.Text) < 0 ||
                int.Parse(textBox3.Text) > 255 || int.Parse(textBox3.Text) < 0 ||
                int.Parse(textBox4.Text) > 255 || int.Parse(textBox4.Text) < 0 ||
                int.Parse(textBox5.Text) > 255 || int.Parse(textBox5.Text) < 0 ||
                int.Parse(textBox6.Text) > 255 || int.Parse(textBox6.Text) < 0)
            {
                MessageBox.Show("IP输入不正确!", "错误");
                return;
            }

            SaveConfig();

            for (int i = 0; i < tableLayoutPanel1.Controls.Count; i++)
            {
                var label = tableLayoutPanel1.Controls[i];
                label.BackColor = Color.FromArgb(0, 240, 240, 240);
            }

            for (int i = int.Parse(textBox5.Text) - 1; i <= int.Parse(textBox6.Text) - 1; i++)
            {
                var tableLabel = SearchLabelFromTableLayoutPanel((i + 1).ToString());
                tableLabel.BackColor = DefaultBackColor;

                var thread = new Thread(() =>
                {
                    System.Net.NetworkInformation.Ping ping = null;
                    var ipAddress = $"{textBox2.Text}.{textBox3.Text}.{textBox4.Text}.{tableLabel.Text}";
                    try
                    {
                        ping = new System.Net.NetworkInformation.Ping();

                        PingReply pingReply = ping.Send(ipAddress, int.Parse(textBox7.Text));
                        var pingable        = pingReply.Status == IPStatus.Success;
                        if (pingable)
                        {
                            tableLabel.BackColor = Color.Green;
                        }
                        else
                        {
                            tableLabel.BackColor = Color.Red;
                        }
                    }
                    catch (Exception exception)
                    {
                        ping = new System.Net.NetworkInformation.Ping();

                        PingReply pingReply  = ping.Send(ipAddress);
                        var pingable         = pingReply?.Status == IPStatus.Success;
                        tableLabel.BackColor = pingable ? Color.Green : Color.Red;

                        Console.WriteLine(ipAddress);
                        Console.WriteLine(exception);
                    }
                    finally
                    {
                        ping?.Dispose();
                    }
                });
                try
                {
                    thread.Start();
                }
                catch (Exception exception)
                {
                    thread.Start();
                }
            }
        }
        public PingItem(string serverName, string ipToPing, double xPos, double yPos) : base()
        {
            Identifier = serverName;
            XPos       = xPos;
            YPos       = yPos;

            var config = ConfigManager.GetPingConfig();

            this.FontSize = config.PingFontSize;

            if (config.GreyBackground)
            {
                this.Background = Brushes.LightGray;
            }
            if (config.PingOutline)
            {
                this.Effect = new DropShadowEffect()
                {
                    ShadowDepth = 0, BlurRadius = 2, Color = Colors.White, Opacity = 1
                };
            }

            _pingIPTimer = new System.Threading.Timer(async(state) =>
            {
                using (var ping = new System.Net.NetworkInformation.Ping())
                {
                    try
                    {
                        var pReply = await ping.SendPingAsync(ipToPing);
                        if (pReply.Status == IPStatus.Success)
                        {
                            _pingAverages.Add((int)pReply.RoundtripTime);
                            _pingErrors = 0;
                        }
                        else if (pReply.Status == IPStatus.TimedOut)
                        {
                            _pingErrors++;
                        }
                    }
                    catch
                    {
                        _pingErrors++;
                    }
                }

                this.Dispatcher.Invoke(() =>
                {
                    // If we fail 3 pings in a row, set the ping to "ERROR"
                    if (_pingErrors == 3)
                    {
                        this.Text = $"{serverName}: ERROR";
                    }
                    else
                    {
                        if (_pingAverages.AveragePing >= 150)
                        {
                            this.Foreground = config.HighPingBrush;
                        }
                        else if (_pingAverages.AveragePing >= 80)
                        {
                            this.Foreground = config.MediumPingBrush;
                        }
                        else
                        {
                            this.Foreground = config.LowPingBrush;
                        }

                        this.Text = $"{serverName}: {_pingAverages.AveragePing}";
                    }
                });
            }, null, 0, 1000);
        }
        public void TraceAsync(IPAddress ipAddress, CancellationToken cancellationToken)
        {
            Task.Run(async() =>
            {
                for (var i = 1; i < MaximumHops + 1; i++)
                {
                    var tasks = new List <Task <Tuple <PingReply, long> > >();

                    for (var y = 0; y < 3; y++)
                    {
                        var i1 = i;

                        tasks.Add(Task.Run(() =>
                        {
                            var stopwatch = new Stopwatch();

                            PingReply pingReply;

                            using (var ping = new System.Net.NetworkInformation.Ping())
                            {
                                stopwatch.Start();

                                pingReply = ping.Send(ipAddress, Timeout, Buffer, new PingOptions {
                                    Ttl = i1, DontFragment = DontFragement
                                });

                                stopwatch.Stop();
                            }

                            return(Tuple.Create(pingReply, stopwatch.ElapsedMilliseconds));
                        }, cancellationToken));
                    }

                    // ReSharper disable once CoVariantArrayConversion, no write operation
                    Task.WaitAll(tasks.ToArray());

                    var ipAddressHop = tasks.FirstOrDefault(x => x.Result.Item1 != null)?.Result.Item1.Address;

                    // Resolve Hostname
                    var hostname = string.Empty;

                    if (ResolveHostname && ipAddressHop != null)
                    {
                        try
                        {
                            var answer = await DnsLookupClient.GetHostNameAsync(ipAddressHop);

                            if (!string.IsNullOrEmpty(answer))
                            {
                                hostname = answer;
                            }
                        }
                        catch { } // Couldn't resolve hostname
                    }

                    OnHopReceived(new TracerouteHopReceivedArgs(i, tasks[0].Result.Item2, tasks[1].Result.Item2, tasks[2].Result.Item2, ipAddressHop, hostname, tasks[0].Result.Item1.Status, tasks[1].Result.Item1.Status, tasks[2].Result.Item1.Status));

                    // Check if finished
                    if (ipAddressHop != null && ipAddress.ToString() == ipAddressHop.ToString())
                    {
                        OnTraceComplete();
                        return;
                    }

                    // Check for cancel
                    if (!cancellationToken.IsCancellationRequested)
                    {
                        continue;
                    }

                    OnUserHasCanceled();

                    return;
                }

                // Max hops reached...
                OnMaximumHopsReached(new MaximumHopsReachedArgs(MaximumHops));
            }, cancellationToken);
        }
Example #52
0
        private void ProcessHop(IPAddress address, IPStatus status, string time)
        {
            Int64 roundTripTime = 0;

            if (status == IPStatus.Success || status == IPStatus.TtlExpired)
            {
                System.Net.NetworkInformation.Ping ping2 = new System.Net.NetworkInformation.Ping();

                try
                {
                    // Do another ping to get the roundtrip time per address.
                    PingReply reply = ping2.Send(address, this.HopTimeOut);
                    roundTripTime = reply.RoundtripTime;
                    status        = reply.Status;
                }
                catch (Exception ex)
                {
                    Log.Info(String.Empty, ex);
                }
                finally
                {
                    ping2.Dispose();
                    ping2 = null;
                }
            }

            if (this.cancel)
            {
                return;
            }

            TraceRouteHopData hop = new TraceRouteHopData(this.counter++, address, roundTripTime, status, time);

            try
            {
                if (status == IPStatus.Success && this.ResolveNames)
                {
                    IPHostEntry entry = Dns.GetHostEntry(address);
                    hop.HostName = entry.HostName;
                }
            }
            catch (SocketException)
            {
                // No such host is known error.
                hop.HostName = String.Empty;
            }

            lock (this.hopList)
                this.hopList.Add(hop);

            if (this.RouteHopFound != null)
            {
                this.RouteHopFound(this, new RouteHopFoundEventArgs(hop, this.Idle));
            }

            this.Idle = address.Equals(this.destinationIP);

            lock (this.hopList)
            {
                if (!this.Idle && this.hopList.Count >= this.HopLimit - 1)
                {
                    this.ProcessHop(this.destinationIP, IPStatus.Success, DateTime.Now.ToLongTimeString());
                }
            }

            if (this.Idle)
            {
                this.OnCompleted();
                this.Dispose();
            }
        }
Example #53
0
    private String getOtherIP()
    {
        String hostName = "";

        try
        {
            // Get the local computer host name.
            hostName = Dns.GetHostName();
            Debug.Log("Computer name :" + hostName);
        }
        catch (Exception e)
        {
            Debug.Log("Exception caught!!!");
            Debug.Log("Source : " + e.Source);
            Debug.Log("Message : " + e.Message);
        }

        IPAddress[] addresses = Dns.GetHostAddresses(hostName);
        Debug.Log($"GetHostAddresses({hostName}) returns:");
        String myAddr = "";

        foreach (IPAddress address in addresses)
        {
            if (address.AddressFamily == AddressFamily.InterNetwork && address.ToString().Substring(0, 3) == "192")
            {
                myAddr = address + "";// My IP
                break;
            }
            Debug.Log($"    {address}");
        }
        Debug.Log("MYADD : " + myAddr);

        p = new System.Net.NetworkInformation.Ping();
        String outIp = pingIps("192.168.43", myAddr);

        if (outIp != "")
        {
            Debug.Log("Success! : " + outIp);
        }
        else
        {
            Debug.Log("Trying pt 2");

            for (int i = 1; i <= 255; i++)
            {
                outIp = pingIps("192.168." + i + ".", myAddr);
                if (outIp != "")
                {
                    break;
                }
            }

            if (outIp != "")
            {
                Debug.Log("\nSuccess! : " + outIp);
            }
            else
            {
                Debug.Log("\nFailure");
            }
        }

        return(outIp);
    }
Example #54
0
        protected static void Scriptlet_Ping(string Destination, int Count)
        {
            if (Count > 10 || Count <= 0)
            {
                CommandInterpreter.WriteToScreenWithNoInterrupt(AppOnlyScope.Status.CommandInformationMessage("Only values from 0 to 10 are interpreted. Using sane value 1."));
                Count = 1;
            }

            try
            {
                CommandInterpreter.WriteToScreenWithNoInterrupt(AppOnlyScope.Status.CommandInformationMessage("Trying to reach '" + Destination + "' " + Count + " time(s)..."));
                for (int i = 1; i <= Count; i++)
                {
                    System.Threading.Thread.Sleep(1000); // increases amount of time between each ping to prevent request spam.

                    var ping   = new System.Net.NetworkInformation.Ping();
                    var result = ping.Send(Destination);

                    if (result.Status != System.Net.NetworkInformation.IPStatus.Success)
                    {
                        Error = "Cannot reach destination host '" + Destination + "'";
                        ValidationResponse.ResponseFromCommandClass     = Error;
                        ValidationResponse.CommandReturnedWasSuccessful = false;
                    }

                    if (result.Status == System.Net.NetworkInformation.IPStatus.TimedOut)
                    {
                        Error = "Timed out reaching '" + Destination + "'";
                        ValidationResponse.ResponseFromCommandClass     = Error;
                        ValidationResponse.CommandReturnedWasSuccessful = false;
                    }

                    if (result.Status == System.Net.NetworkInformation.IPStatus.Unknown)
                    {
                        Error = "Unknown response received from '" + Destination + "'";
                        ValidationResponse.ResponseFromCommandClass     = Error;
                        ValidationResponse.CommandReturnedWasSuccessful = false;
                    }

                    if (result.Status == System.Net.NetworkInformation.IPStatus.TimeExceeded)
                    {
                        Error = "The destination server for '" + Destination + "' discarded the packet sent to verify its status";
                        ValidationResponse.ResponseFromCommandClass     = Error;
                        ValidationResponse.CommandReturnedWasSuccessful = false;
                    }

                    if (result.Status == System.Net.NetworkInformation.IPStatus.NoResources)
                    {
                        Error = "Insufficient network resources to process this command.";
                        ValidationResponse.ResponseFromCommandClass     = Error;
                        ValidationResponse.CommandReturnedWasSuccessful = false;
                    }

                    if (result.Status == System.Net.NetworkInformation.IPStatus.Success)
                    {
                        IPHostEntry hostEntry;
                        hostEntry = Dns.GetHostEntry(Destination);
                        string IPAddress     = hostEntry.AddressList[0].ToString();
                        string MessageResult = "Successfully received reply from '" + Destination + "' (" + IPAddress + ") (" + i + ")";
                        CommandInterpreter.WriteToScreenWithNoInterruptNoSpaces(AppOnlyScope.Status.CommandInformationMessage(MessageResult));
                        ValidationResponse.CommandReturnedWasSuccessful = true;
                    }
                }

                CommandInterpreter.WriteToScreenWithNoInterrupt(AppOnlyScope.Status.CommandInformationMessage("Operation completed."));
            }

            catch (Exception PingLocationException)
            {
                ValidationResponse.ResponseFromCommandClass     = PingLocationException.Message;
                ValidationResponse.CommandReturnedWasSuccessful = false;
            }
        }
Example #55
0
        public void ScanAsync(IPAddress[] ipAddresses, IPScannerOptions ipScannerOptions, CancellationToken cancellationToken)
        {
            // Start the scan in a separat task
            Task.Run(() =>
            {
                _progressValue = 0;

                // Modify the ThreadPool for better performance
                ThreadPool.GetMinThreads(out int workerThreads, out int completionPortThreads);
                ThreadPool.SetMinThreads(workerThreads + ipScannerOptions.Threads, completionPortThreads + ipScannerOptions.Threads);

                try
                {
                    var parallelOptions = new ParallelOptions
                    {
                        CancellationToken      = cancellationToken,
                        MaxDegreeOfParallelism = ipScannerOptions.Threads
                    };

                    Parallel.ForEach(ipAddresses, parallelOptions, ipAddress =>
                    {
                        var pingInfo = new PingInfo();
                        var pingable = false;

                        // PING
                        using (var ping = new System.Net.NetworkInformation.Ping())
                        {
                            for (int i = 0; i < ipScannerOptions.ICMPAttempts; i++)
                            {
                                try
                                {
                                    var pingReply = ping.Send(ipAddress, ipScannerOptions.ICMPTimeout, ipScannerOptions.ICMPBuffer);

                                    if (pingReply != null && IPStatus.Success == pingReply.Status)
                                    {
                                        pingInfo = new PingInfo(pingReply.Address, pingReply.Buffer.Count(), pingReply.RoundtripTime, pingReply.Options.Ttl, pingReply.Status);

                                        pingable = true;
                                        break; // Continue with the next checks...
                                    }

                                    if (pingReply != null)
                                    {
                                        pingInfo = new PingInfo(ipAddress, pingReply.Status);
                                    }
                                }
                                catch (PingException)
                                {
                                }

                                // Don't scan again, if the user has canceled (when more than 1 attempt)
                                if (cancellationToken.IsCancellationRequested)
                                {
                                    break;
                                }
                            }
                        }

                        if (pingable || ipScannerOptions.ShowScanResultForAllIPAddresses)
                        {
                            // DNS
                            var hostname = string.Empty;

                            if (ipScannerOptions.ResolveHostname)
                            {
                                var options = new DNSLookupOptions()
                                {
                                    UseCustomDNSServer = ipScannerOptions.UseCustomDNSServer,
                                    CustomDNSServers   = ipScannerOptions.CustomDNSServer,
                                    Port             = ipScannerOptions.DNSPort,
                                    Attempts         = ipScannerOptions.DNSAttempts,
                                    Timeout          = ipScannerOptions.DNSTimeout,
                                    TransportType    = ipScannerOptions.DNSTransportType,
                                    UseResolverCache = ipScannerOptions.DNSUseResolverCache,
                                    Recursion        = ipScannerOptions.DNSRecursion,
                                };

                                hostname = DNSLookup.ResolvePTR(ipAddress, options).Item2.FirstOrDefault();
                            }

                            // ARP
                            PhysicalAddress macAddress = null;
                            var vendor = string.Empty;

                            if (ipScannerOptions.ResolveMACAddress)
                            {
                                // Get info from arp table
                                var arpTableInfo = ARP.GetTable().FirstOrDefault(p => p.IPAddress.ToString() == ipAddress.ToString());

                                if (arpTableInfo != null)
                                {
                                    macAddress = arpTableInfo.MACAddress;
                                }

                                // Check if it is the local mac
                                if (macAddress == null)
                                {
                                    var networkInferfaceInfo = NetworkInterface.GetNetworkInterfaces().FirstOrDefault(p => p.IPv4Address.Contains(ipAddress));

                                    if (networkInferfaceInfo != null)
                                    {
                                        macAddress = networkInferfaceInfo.PhysicalAddress;
                                    }
                                }

                                // Vendor lookup
                                if (macAddress != null)
                                {
                                    var info = OUILookup.Lookup(macAddress.ToString()).FirstOrDefault();

                                    if (info != null)
                                    {
                                        vendor = info.Vendor;
                                    }
                                }
                            }

                            OnHostFound(new HostFoundArgs(pingInfo, hostname, macAddress, vendor));
                        }

                        IncreaseProcess();
                    });

                    OnScanComplete();
                }
                catch (OperationCanceledException)  // If user has canceled
                {
                    // Check if the scan is already complete...
                    if (ipAddresses.Length == _progressValue)
                    {
                        OnScanComplete();
                    }
                    else
                    {
                        OnUserHasCanceled();
                    }
                }
                finally
                {
                    // Reset the ThreadPool to default
                    ThreadPool.GetMinThreads(out workerThreads, out completionPortThreads);
                    ThreadPool.SetMinThreads(workerThreads - ipScannerOptions.Threads, completionPortThreads - ipScannerOptions.Threads);
                }
            }, cancellationToken);
        }
Example #56
0
        /// <summary>
        /// Used to Ping a device on the network
        /// </summary>
        /// <returns>A IPStatus value, True if the device was successfully pinged</returns>
        public static IPStatus PingStatus(string Name, string Domain)
        {
            var p = new System.Net.NetworkInformation.Ping();

            return(p.Send(Name + Domain, 2700).Status);
        }
Example #57
0
        public void SendTraceRoute(string Address, int Timeout, int MaxHops)
        {
            TracerouteDataStructure tds = new TracerouteDataStructure();
            //yield return tds;
            string hostname = Address;
            // following are the defaults for the "traceroute" command in unix.
            //timeout before going to another thing
            int timeout = Timeout;
            //max number of servers/hops to jump through before stopping
            int       maxTTL        = MaxHops;
            int       currentmaxttl = 0;
            Stopwatch g             = new Stopwatch();
            Stopwatch g2            = new Stopwatch();

            byte[] buffer =
            {
                101, 108, 108, 111,  32, 116, 104, 101,
                114, 101,  32,  99,  97, 110,  32, 121,
                111, 117,  32, 115, 101, 101,  32, 116,
                104, 105, 115,  32, 112, 105, 110, 103
            };
            System.Net.NetworkInformation.Ping pinger = new System.Net.NetworkInformation.Ping();
            //PingStatusText = $"Traceroute Started on {hostname}" + Environment.NewLine;
            for (int ttl = 1; ttl <= maxTTL; ttl++)
            {
                currentmaxttl++;
                g.Start();
                g2.Start();
                PingOptions options = new PingOptions(ttl, true);
                PingReply   reply   = null;
                bool        err     = false;
                //send ping
                try
                {
                    reply = pinger.Send(hostname, timeout, buffer, options);
                }
                catch (PingException es)
                {
                    tds.Status = "PingException. Stopping..."; err = true;
                    tds.Route  = $"{ es.Message}"; break;
                }
                catch (ArgumentException es)
                {
                    tds.Status = "Argument Exception. Stopping..."; err = true;
                    tds.Route  = $"{ es.Message} { es.ParamName}"; break;
                }
                catch (Exception exc)
                {
                    tds.Status = "Generat Error Stopping..."; err = true;
                    tds.Route  = $"{ exc.Message}"; break;
                }
                if (err)
                {
                    OnStatusMessage?.Invoke(tds);
                }
                if (reply != null)
                {
                    tds.AddressPosition = $"{ttl}";
                    tds.Interval        = $"{g2.ElapsedMilliseconds} ms";
                    tds.Route           = $"{reply.Address}";
                    tds.TotalTime       = $"{g.ElapsedMilliseconds}";
                    if (reply.Status == IPStatus.TtlExpired)
                    {
                        // TtlExpired means we've found an address, but there are more addresses
                        tds.Status = "Success ->";
                        g2.Reset(); OnStatusMessage?.Invoke(tds);
                        continue;
                    }
                    if (reply.Status == IPStatus.BadRoute)
                    {
                        tds.Status = "Bad Route ->";
                    }
                    if (reply.Status == IPStatus.BadDestination)
                    {
                        tds.Status = "Bad Destination ->";
                    }
                    if (reply.Status == IPStatus.DestinationHostUnreachable)
                    {
                        tds.Status = "Bad Destination ->";
                    }
                    if (reply.Status == IPStatus.DestinationPortUnreachable)
                    {
                        tds.Status = "Bad Destination ->";
                    }
                    if (reply.Status == IPStatus.ParameterProblem)
                    {
                        tds.Status = "Bad Destination ->";
                    }
                    if (reply.Status == IPStatus.TimedOut)
                    {
                        // TimedOut means this ttl is no good, we should continue searching
                        tds.Status = "Timeout"; OnStatusMessage?.Invoke(tds);
                        continue;
                    }
                    if (reply.Status == IPStatus.Success)
                    {
                        // Success means the tracert has completed
                        //traceRouteViewModel.AddNewMessage($" -- ICMP Trace route completed : {reply.Address} in {g.ElapsedMilliseconds} ms --");
                        tds.Status = "ICMP Traceroute Complete";
                        //PingStatusText = "Traceroute Completed" + Environment.NewLine;
                        //PingStats += $"TraceRoute Completed." + Environment.NewLine;
                        g.Stop();
                    }
                    OnStatusMessage?.Invoke(tds);
                }
                // if we ever reach here, we're finished, so break
                break;
            }
            if (currentmaxttl >= maxTTL)
            {
                tds.Status = "Max Hops Exceeded. Stopping...";
                OnStatusMessage?.Invoke(tds);
                //PingStatusText = $"Traceroute Stopped. Exceded {maxTTL} Hops." + Environment.NewLine;
            }
        }
Example #58
0
        public void TraceAsync(IPAddress ipAddress, TracerouteOptions traceOptions, CancellationToken cancellationToken)
        {
            Task.Run(() =>
            {
                byte[] buffer   = new byte[traceOptions.Buffer];
                int maximumHops = traceOptions.MaximumHops + 1;

                int hop = 1;

                do
                {
                    List <Task <Tuple <PingReply, long> > > tasks = new List <Task <Tuple <PingReply, long> > >();

                    for (int i = 0; i < 3; i++)
                    {
                        tasks.Add(Task.Run(() =>
                        {
                            Stopwatch stopwatch = new Stopwatch();

                            PingReply pingReply;

                            using (System.Net.NetworkInformation.Ping ping = new System.Net.NetworkInformation.Ping())
                            {
                                stopwatch.Start();

                                pingReply = ping.Send(ipAddress, traceOptions.Timeout, buffer, new System.Net.NetworkInformation.PingOptions()
                                {
                                    Ttl = hop, DontFragment = traceOptions.DontFragement
                                });

                                stopwatch.Stop();
                            }

                            return(Tuple.Create(pingReply, stopwatch.ElapsedMilliseconds));
                        }));
                    }

                    Task.WaitAll(tasks.ToArray());

                    IPAddress ipAddressHop = tasks.FirstOrDefault(x => x.Result.Item1 != null).Result.Item1.Address;

                    string hostname = string.Empty;

                    try
                    {
                        if (ipAddressHop != null)
                        {
                            hostname = Dns.GetHostEntry(ipAddressHop).HostName;
                        }
                    }
                    catch (SocketException) { } // Couldn't resolve hostname

                    OnHopReceived(new TracerouteHopReceivedArgs(hop, tasks[0].Result.Item2, tasks[1].Result.Item2, tasks[2].Result.Item2, ipAddressHop, hostname, tasks[0].Result.Item1.Status, tasks[1].Result.Item1.Status, tasks[2].Result.Item1.Status));

                    if (ipAddressHop != null)
                    {
                        if (ipAddressHop.ToString() == ipAddress.ToString())
                        {
                            OnTraceComplete();
                            return;
                        }
                    }

                    hop++;
                } while (hop < maximumHops && !cancellationToken.IsCancellationRequested);

                if (cancellationToken.IsCancellationRequested)
                {
                    OnUserHasCanceled();
                }
                else if (hop == maximumHops)
                {
                    OnMaximumHopsReached(new MaximumHopsReachedArgs(traceOptions.MaximumHops));
                }
            }, cancellationToken);
        }
Example #59
0
        private void ButtonStart_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(this.TextHost.Text.Trim()))
            {
                this.TextHost.Focus();
                return;
            }

            this.TextHost.Text = this.TextHost.Text.Trim();

            this.ButtonStart.Enabled = false;
            this.TextHost.Enabled    = false;
            Application.DoEvents();

            if (!this.pingRunning)
            {
                IPAddress[] list = null;
                var         msg  = string.Empty;
                try
                {
                    list = Dns.GetHostAddresses(this.TextHost.Text);
                    if (list != null)
                    {
                        this.destination = list[0].ToString();

                        IPAddress ip;
                        this.hostName = IPAddress.TryParse(this.TextHost.Text, out ip) ? this.destination
                            : Dns.GetHostEntry(this.TextHost.Text).HostName;

                        this.counter      = 1;
                        this.currentDelay = (int)this.DelayNumericUpDown.Value;
                        this.pingList     = new List <PingReplyData>();

                        if (this.pingSender == null)
                        {
                            this.pingSender = new System.Net.NetworkInformation.Ping();
                            this.pingSender.PingCompleted += this.pingSender_PingCompleted;
                        }

                        this.pingRunning = true;
                        this.pingReady   = true;

                        // Making sure previous timer is cleared before starting a new one
                        if (this.timer != null)
                        {
                            this.timer.Dispose();
                            this.timer = null;
                        }

                        // Start thread timer to start TrySend method for every ms in the specified delay updown box
                        var callback = new TimerCallback(this.TryPing);
                        this.timer = new Timer(callback, null, this.currentDelay, this.currentDelay);
                    }
                }
                catch (SocketException)
                {
                    msg = string.Format("Could not resolve address: {0}", this.TextHost.Text);
                    this.pingRunning = false;
                }
                catch (ArgumentException)
                {
                    msg = string.Format("Hostname or IP-Address is invalid: {0}", this.TextHost.Text);
                    this.pingRunning = false;
                }
                catch (Exception ex)
                {
                    msg = string.Format("An error occured trying to ping {0}", this.TextHost.Text);
                    Logging.Info(msg, ex);
                    this.pingRunning = false;
                }
                finally
                {
                    if (!this.pingRunning)
                    {
                        MessageBox.Show(msg, "Ping Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        this.ResetForm();
                    }
                }
            }
        }
        public static string SendPing(string host, int count)
        {
            string[] status = new string[count];

            using (Ping ping = new Ping())
            {
                PingReply reply;
                //byte[] buffer = Encoding.ASCII.GetBytes(new string('a', 32));
                for (int i = 0; i < count; i++)
                {
                    reply = ping.Send(host, 3000);
                    if (reply.Status == IPStatus.Success)
                    {
                        status[i] = reply.RoundtripTime.ToString() + " ms";
                    }
                    else
                    {
                        status[i] = "Timeout";
                    }
                    Thread.Sleep(100);
                }
            }

            return string.Join(", ", status);
        }