SendAsync() public method

public SendAsync ( System address, int timeout, byte buffer, System options, object userToken ) : void
address System
timeout int
buffer byte
options System
userToken object
return void
Beispiel #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);
            }
        }
Beispiel #2
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);
         }
     }
 }
Beispiel #3
0
 private void Ping(string host, int attempts, int timeout, bool lastadress = false)
 {
     for (int i = 0; i < attempts; i++)
     {
         new Thread(delegate()
         {
             try
             {
                 System.Net.NetworkInformation.Ping ping = new System.Net.NetworkInformation.Ping();
                 if (lastadress == true)
                 {
                     ping.PingCompleted += new PingCompletedEventHandler(LastPingCompleted);
                 }
                 else
                 {
                     ping.PingCompleted += new PingCompletedEventHandler(PingCompleted);
                 }
                 System.Diagnostics.Debug.Print("Ping to " + host);
                 ping.SendAsync(host, timeout, host);
             }
             catch
             {
                 // Do nothing and let it try again until the attempts are exausted.
                 // Exceptions are thrown for normal ping failurs like address lookup
                 // failed.  For this reason we are supressing errors.
             }
         }).Start();
     }
 }
Beispiel #4
0
        /// <summary>
        /// Ping
        /// </summary>
        /// <param name="host"></param>
        /// <param name="att"></param>
        /// <param name="time"></param>
        public void Ping(string host, int att, int time)
        {
            for (int i = 0; i < att; i++)
            {
                bool caught = false;

                new Thread(delegate()
                {
                    try
                    {
                        System.Net.NetworkInformation.Ping ping = new System.Net.NetworkInformation.Ping();
                        ping.PingCompleted += new PingCompletedEventHandler(PingCompleted);
                        ping.SendAsync(host, time, host);
                    }
                    catch
                    {
                        caught = true;
                        Variables.counter++;
                    }
                    if (!caught)
                    {
                        Thread.CurrentThread.Abort();
                    }
                }).Start();
            }
        }
        private void SendPingAsync(string ip)
        {
            var ping = new System.Net.NetworkInformation.Ping();

            ping.PingCompleted += OnPingCompleted;
            ping.SendAsync(ip, pingTimeout, ip);
        }
Beispiel #6
0
        public void Ping(string host, int attempts, int timeout)
        {
            //    CreateDebugFile("#DEBUG  :inside ping");
            SetLoading(true);
            for (int i = 0; i < attempts; i++)
            {
                new Thread(delegate()
                {
                    //  SetLoading(true);
                    try
                    {
                        System.Net.NetworkInformation.Ping ping = new System.Net.NetworkInformation.Ping();
                        ping.PingCompleted += new PingCompletedEventHandler(PingCompleted);

                        ping.SendAsync(host, timeout, host);
                    }
                    catch (Exception ex)
                    {
                        //      CreateDebugFile(ex.Message);
                        // Do nothing and let it try again until the attempts are exausted.
                        // Exceptions are thrown for normal ping failurs like address lookup
                        // failed.  For this reason we are supressing errors.
                    }
                }).Start();
            }
            // SetLoading(false);
        }
        public Task<PingReply> PingAsync(string address)
        {
            var tcs = new TaskCompletionSource<PingReply>();

            t = new Thread(new ThreadStart(() =>
            {
                Ping ping = new Ping();
                ping.PingCompleted += (obj, sender) =>
                {
                    tcs.SetResult(sender.Reply);
                };

                ping.SendAsync(address, new object());

                if (tcs.Task.Result.Status.Equals(IPStatus.Success) || tcs.Task.Result.Status.Equals(IPStatus.TimedOut))
                {
                    isPinged = true;
                }
            }
              ));

            t.Start();

            return tcs.Task;
        }
Beispiel #8
0
        public async Task <IPingResponse> Ping(IPAddress ipadrress)
        {
            try
            {
                var ping = new System.Net.NetworkInformation.Ping();
                var taskCompletionSource = new TaskCompletionSource <PingCompletedEventArgs>();

                void OnPingOnPingCompleted(object s, PingCompletedEventArgs e)
                {
                    taskCompletionSource.SetResult(e);
                }

                ping.PingCompleted += OnPingOnPingCompleted;
                const int timeoutInMilliseconds = 1000;
                ping.SendAsync(ipadrress, timeoutInMilliseconds, ipadrress);


                var responsEventArgs = await taskCompletionSource.Task.ConfigureAwait(false);

                var result = _pingResponseUtil.Convert(responsEventArgs);
                return(result);
            }
            catch (PingException e)
            {
                return(new PingResponse(ipadrress, TimeSpan.Zero, IPStatus.DestinationNetworkUnreachable, ipadrress));
            }
        }
Beispiel #9
0
        public static void Main(string[] args)
        {
            if (args.Length == 0)
            {
                throw new ArgumentException("Enter the ip address: ");
            }
            string         adressWWW = args[0];
            AutoResetEvent waiter    = new AutoResetEvent(false);

            Ping pingSender = new System.Net.NetworkInformation.Ping();

            pingSender.PingCompleted += new PingCompletedEventHandler(PingCompletedCallback);

            string data = "AAA!";

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

            int timeout = 3600;

            PingOptions options = new PingOptions(64, true);

            Console.WriteLine("Time to live: {0}", options.Ttl);
            Console.WriteLine("Do not fragment packages: {0}", options.DontFragment);

            pingSender.SendAsync(adressWWW, timeout, byteBuffer, options, waiter);

            waiter.WaitOne();
            Console.WriteLine("The ping command has ended.");
            Console.ReadKey();
        }
Beispiel #10
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("错误!");
                }
            }
        }
        /// <summary>
        /// Notifies the hub about the updatel
        /// </summary>
        public void Submit()
        {
            var ping = new Ping();

            string hostName = Hub.AbsoluteUri;
            string payload = Topic.AbsoluteUri;
            ping.SendAsync(hostName, TimeOut, payload.ToCharArray());
        }
Beispiel #12
0
 static Task<PingReply> PingAsync(string address)
 {
     var tcs = new TaskCompletionSource<PingReply>();
       Ping ping = new Ping();
       ping.PingCompleted += (obj, sender) => {
     tcs.SetResult(sender.Reply);
       };
       ping.SendAsync(address, new object());
       return tcs.Task;
 }
Beispiel #13
0
        public void Ping(Action completedAction)
        {
            Ping ping = new Ping();
            PingOptions pingOptions = new PingOptions();

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

            ping.PingCompleted += new PingCompletedEventHandler(ping_PingCompleted);
            ping.SendAsync(this.Host, 500, buffer, pingOptions, completedAction);
        }
Beispiel #14
0
	public void Connect()
	{
		// We first try to ping twitch.tv to make sure it's reachable
		string data = "abcdefghijklmopqrstuvwxyz012345";
		byte[] buffer = Encoding.ASCII.GetBytes(data);
		int timeout = 5000;
		Ping ping = new Ping();
		ping.PingCompleted += HandleConnectionPingCompleted;
		PingOptions pingOption = new PingOptions(64, true);
		ping.SendAsync(Hostname, timeout, buffer, pingOption);
	}
Beispiel #15
0
        public void Execute()
        {
            //
            // 同期での送信.
            //
            var hostName = "localhost";
            var timeOut = 3000;

            var p = new Ping();
            var r = p.Send(hostName, timeOut);

            if (r.Status == IPStatus.Success)
            {
                Output.WriteLine("Ping.Send() Success.");
            }
            else
            {
                Output.WriteLine("Ping.Send() Failed.");
            }

            //
            // 非同期での送信.
            //
            hostName = "www.google.com";
            object userToken = null;

            p.PingCompleted += (s, e) =>
            {
                if (e.Cancelled)
                {
                    Output.WriteLine("Cancelled..");
                    return;
                }

                if (e.Error != null)
                {
                    Output.WriteLine(e.Error.ToString());
                    return;
                }

                if (e.Reply.Status != IPStatus.Success)
                {
                    Output.WriteLine("Ping.SendAsync() Failed");
                    return;
                }

                Output.WriteLine("Ping.SendAsync() Success.");
            };

            p.SendAsync(hostName, timeOut, userToken);
            Thread.Sleep(3000);
        }
Beispiel #16
0
        /*THREADS*/


        #region Асинхронная проверка пинга

        private void SendPing(string IP)
        {
            //AutoResetEvent resetEvent = new AutoResetEvent(false);
            try
            {
                System.Net.NetworkInformation.Ping pingSender = new System.Net.NetworkInformation.Ping();
                pingSender.PingCompleted += new PingCompletedEventHandler(pingSender_Complete);
                byte[]      packetData    = Encoding.ASCII.GetBytes("................................");
                PingOptions packetOptions = new PingOptions(50, true);
                pingSender.SendAsync(IP, 5000, packetData, packetOptions, new AutoResetEvent(false));
            }
            catch { }
        }
Beispiel #17
0
 public void ping_Async(String sHostNameOrAddressToPing)
 {
     try
     {
         var pPing = new System.Net.NetworkInformation.Ping();
         pPing.PingCompleted += pPing_PingCompleted;
         pPing.SendAsync(sHostNameOrAddressToPing, sHostNameOrAddressToPing);
     }
     catch (Exception ex)
     {
         PublicDI.log.error("in Ping: {0}", ex.Message);
     }
 }
Beispiel #18
0
 public void PingHosts(string[] hosts, int count, int timeOutMs)
 {
     for (var i = 0; i < count; i++) {
         Console.WriteLine("{0} - {1}", DateTime.Now.ToLongTimeString(), string.Join(", ", hosts));
         foreach (var host in hosts) {
             var p = new Ping();
             p.PingCompleted += PingCompleted;
             p.SendAsync(host, 1500, host);
         }
         Thread.Sleep(timeOutMs);
         Console.WriteLine("\n");
     }
 }
Beispiel #19
0
 public void ping_Async(String sHostNameOrAddressToPing)
 {
     try
     {
         var pPing = new System.Net.NetworkInformation.Ping();
         pPing.PingCompleted += pPing_PingCompleted;
         pPing.SendAsync(sHostNameOrAddressToPing, sHostNameOrAddressToPing);
     }
     catch (Exception ex)
     {
         DI.log.error("in Ping: {0}", ex.Message);
     }
 }
        public static void ScanIPs()
        {


            //string hostName = Dns.GetHostName(); // Retrive the Name of HOST

            //Console.WriteLine(hostName);

            // Get the IP

            //string myIP = Dns.GetHostByName(hostName).AddressList[0].ToString();

            string myIP = "192.168.1.1";
            var bytes = IPAddress.Parse(myIP).GetAddressBytes();
            // set the value here
            bytes[3] = 0;



            IPAddress ipAddress = new IPAddress(bytes);
            var IPaddress1 = IPAddress.Parse(myIP).GetAddressBytes()[0].ToString() + "." + IPAddress.Parse(myIP).GetAddressBytes()[1].ToString() + "." + IPAddress.Parse(myIP).GetAddressBytes()[2].ToString() + ".";

            Console.WriteLine("My IP Address is :" + myIP);
            Console.WriteLine("Network :" + IPaddress1);
            //Console.ReadLine();




            countdown = new CountdownEvent(1);
            Stopwatch sw = new Stopwatch();
            sw.Start();
            //string ipBase = "10.0.0.";
            for (int i = 1; i < 255; i++)
            {
                string ip = IPaddress1 + i.ToString();

                Ping p = new Ping();
                p.PingCompleted += new PingCompletedEventHandler(p_PingCompleted);
                countdown.AddCount();
                p.SendAsync(ip, 100, ip);
            }
            countdown.Signal();
            countdown.Wait();
            sw.Stop();
            TimeSpan span = new TimeSpan(sw.ElapsedTicks);
            //Console.WriteLine("Took {0} milliseconds. {1} hosts active.", sw.ElapsedMilliseconds, upCount);
            //Console.WriteLine("\nPress any key to continue...");
            //Console.ReadKey();
        }
Beispiel #21
0
        public string MyPing()
        {
            string ip1 = getIP();
             for(int i = 0; i < 255; i++)
            {
                Ping myPing=new Ping();
                myPing.PingCompleted += new PingCompletedEventHandler(_myPing_PingCompleted);
                // gethost ip 
                string pingIP =ip1  + i.ToString();
                myPing.SendAsync(pingIP, 1000, null);

            }
            return pingstr; 
        }
Beispiel #22
0
        private void SendPing()
        {
            System.Net.NetworkInformation.Ping pingSender = new System.Net.NetworkInformation.Ping();

            pingSender.PingCompleted += new PingCompletedEventHandler(pingTest_Complete);

            // Create a buffer of 32 bytes.
            byte[] _data = Encoding.ASCII.GetBytes("................................");

            PingOptions Options = new PingOptions(50, true);

            // Send the ping asynchronously
            pingSender.SendAsync("www.google.com", 2000, _data, Options);
        }
Beispiel #23
0
 static Task<PingReply> PingAsync(string address)
 {
     var tcs = new TaskCompletionSource<PingReply>();
     Ping ping = new Ping();
     ping.PingCompleted += (obj, sender) =>
     {
         tcs.SetResult(sender.Reply);
     };
     ping.SendAsync(address, 200, new object());
     if (tcs.Task.Status.ToString() != "Success")
     {
         fail_count++;
     }
     return tcs.Task;
 }
Beispiel #24
0
        private void SendPing()
        {
            System.Net.NetworkInformation.Ping pingSender = new System.Net.NetworkInformation.Ping();

            // Create an event handler for ping complete
            pingSender.PingCompleted += new PingCompletedEventHandler(pingSender_Complete);

            // Create a buffer of 32 bytes of data to be transmitted.
            byte[] packetData = Encoding.ASCII.GetBytes("................................");

            // Jump though 50 routing nodes tops, and don't fragment the packet
            PingOptions packetOptions = new PingOptions(50, true);

            // Send the ping asynchronously
            pingSender.SendAsync(txtIP.Text, 5000, packetData, packetOptions, resetEvent);
        }
        public static void RefreshServerList()
        {
            IPAddress ipAddress = Array.FindAll(Dns.GetHostAddresses(Dns.GetHostName()), a => a.AddressFamily == AddressFamily.InterNetwork).First();
            string[] baseIP = ipAddress.ToString().Split('.');

            for (int j = Int32.Parse(baseIP[2]); j < Int32.Parse(baseIP[2]) + 5; j++) {
                for (int i = 0; i < 255; i++) {
                    try {
                        IPAddress ip = IPAddress.Parse(baseIP[0] + "." + baseIP[1] + "." + j + "." + i);

                        Ping ping = new Ping();
                        ping.PingCompleted += new PingCompletedEventHandler(PingCompleted);
                        ping.SendAsync(ip, 600, ip);
                    } catch (Exception) { }
                }
            }
        }
Beispiel #26
0
        public static void BeginPingHost(string hostNameOrAddress, int TimeOut, EventHandler <PingCallBackEventArgs> pingCallBack, object userState)
        {
            var PingSender = new System.Net.NetworkInformation.Ping();

            PingOptions Options = new PingOptions();

            Options.DontFragment = true;

            PingSender.PingCompleted += PingSender_PingCompleted;

            var obj = new PrivatePingUserState()
            {
                PingCallBack = pingCallBack, UserState = userState
            };

            PingSender.SendAsync(hostNameOrAddress, TimeOut, testSendData, obj);
        }
Beispiel #27
0
        private void btnDomain2IP_Click(object sender, EventArgs e)
        {
            for (int i = 0; i < dataGridView1.Rows.Count - 1; i++)
            {
                try
                {
                    Ping myPing = new Ping();
                    myPing.PingCompleted += new PingCompletedEventHandler(_myPing_PingCompleted);
                    string hostName = dataGridView1[0, i].Value.ToString();
                    myPing.SendAsync(hostName, 1, i);
                }
                catch
                {

                }

            }
        }
Beispiel #28
0
 public Ping(string ipAddress, int timeout = 10, string data = null, PingReplyArrivedEventHandler PingReplyArrivedHandler = null)
 {
     if (PingReplyArrivedHandler != null)
     {
         PingReplyArrived += PingReplyArrivedHandler;
     }
     try
     {
         ping = new System.Net.NetworkInformation.Ping();
         ping.PingCompleted += PingResult;
         var dataToSend = String.IsNullOrEmpty(data) ? "ping".ToByteArray() : data.ToByteArray();
         ping.SendAsync(ipAddress, timeout, dataToSend, null);
     }
     catch
     {
         Dispose();
     }
 }
Beispiel #29
0
        /// <inheritdoc />
        /// <summary>
        ///     Starts the ping process.
        ///     Enqueueing new ip addresses for ping is disabled during scantime
        /// </summary>
        public override void Start()
        {
            base.Start();

            var       pingLimiter = _runningPingScanners;
            IPAddress lastResult;

            while (pingLimiter <= MaxConcurrentScans && (lastResult = GetNext()) != null)
            {
                var pingSender = new System.Net.NetworkInformation.Ping();
                pingSender.PingCompleted += PingCompletedCallback;
                pingSender.SendAsync(lastResult, (int)TimeOut.TotalMilliseconds, new byte[32].Propagate((byte)'#'), _pingOptions);

                pingLimiter++;
            }

            _runningPingScanners = pingLimiter;
        }
Beispiel #30
0
        protected static void MonitorStorageServer(string address)
        {          
            Ping pingSender = new Ping();

            pingSender.PingCompleted += new PingCompletedEventHandler(PingCompletedCallback);

            // Create a buffer of 32 bytes of data to be transmitted.
            string data = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
            byte[] buffer = Encoding.ASCII.GetBytes(data);

            //set options
            PingOptions options = new PingOptions(64, true);

            //send ping (async)
            pingSender.SendAsync(address, timerAndPingTimeout, buffer, options, address);



        }
Beispiel #31
0
		public void SendAsyncIPV4Fails()
		{
			var testIp = IPAddress.Parse("192.0.2.0");
			var ping = new Ping ();
			PingReply reply = null;

			using (var waiter = new AutoResetEvent (false)) {
				ping.PingCompleted += new PingCompletedEventHandler ( 
					(s, e) => {
						reply = e.Reply;
						(e.UserState as AutoResetEvent) ?.Set ();
					});

				ping.SendAsync (testIp, waiter);

				waiter.WaitOne (TimeSpan.FromSeconds (8));
			}

			Assert.AreNotEqual (IPStatus.Success, reply.Status);
		}
Beispiel #32
0
        private void handlePing(DashboardItem item)
        {
            AutoResetEvent waiter = new AutoResetEvent(false);
            var            ping   = new System.Net.NetworkInformation.Ping();

            ping.PingCompleted += (s, e) =>
            {
                if (e.Reply != null && e.Reply.Status == IPStatus.Success)
                {
                    item.value = "ok";
                }
                else
                {
                    item.value = "offline";
                }
                waiter.Set();
            };
            ping.SendAsync(item.parameter, 100, null);
            waiter.WaitOne();
        }
Beispiel #33
0
 public void Ping(string host, int attempts, int timeout)
 {
     for (int i = 0; i < attempts; i++)
     {
         new Thread(delegate()
         {
             try
             {
                 System.Net.NetworkInformation.Ping ping = new System.Net.NetworkInformation.Ping();
                 ping.PingCompleted += new PingCompletedEventHandler(PingCompleted);
                 ping.SendAsync(host, timeout, host);
             }
             catch
             {
                 // Do nothing and let it try again until the attempts are exausted.
                 // Exceptions are thrown for normal ping failurs like address lookup
                 // failed.  For this reason we are supressing errors.
             }
         }).Start();
     }
 }
        //获取计算机列表
        private void EnumComputers()
        {
            try
            {
                string local_ip = BathClass.get_local_ip();
                string ip_zone = local_ip.Substring(0, local_ip.LastIndexOf('.') + 1);
                for (int i = 0; i <= 255; i++)
                {
                    Ping myPing;
                    myPing = new Ping();
                    myPing.PingCompleted += new PingCompletedEventHandler(myPing_PingCompleted);

                    string pingIP = ip_zone + i.ToString();
                    myPing.SendAsync(pingIP, 1000, null);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
Beispiel #35
0
    IEnumerator GetIP()
    {
        yield return(new WaitForSeconds(1f));

        //获取本地机器名
        string _myHostName = Dns.GetHostName();
        //获取本机IP
        string _myHostIP = Dns.GetHostEntry(_myHostName).AddressList[0].ToString();

        //截取IP网段
        string ipDuan = _myHostIP.Remove(_myHostIP.LastIndexOf('.'));

        //string ipDuan = "192.168.0";
        //枚举网段计算机
        for (int i = 1; i <= 255; i++)
        {
            System.Net.NetworkInformation.Ping myPing = new System.Net.NetworkInformation.Ping();
            myPing.PingCompleted += new PingCompletedEventHandler(_myPing_PingCompleted);
            string pingIP = ipDuan + "." + i.ToString();
            myPing.SendAsync(pingIP, 500, null);
        }
    }
Beispiel #36
0
        private void GeneratePing()
        {
            try
            {
                // Set options for transmission:
                // The data can go through 64 gateways or routers
                // before it is destroyed, and the data packet
                // cannot be fragmented.
                PingOptions options = new PingOptions(64, true);

                // Send the ping asynchronously.
                // Use the waiter as the user token.
                // When the callback completes, it can wake up this thread.
                pingSender.SendAsyncCancel();
                pingSender.SendAsync(ipAddress, pingFrequency, pingBuffer, options);
            }
            catch (Exception ex)
            {
                Logger.Instance.LogMessage(TracingLevel.ERROR, $"GeneratePing failed: {ex}");
                pingCanceled = true;
            }
        }
Beispiel #37
0
    public static void Pingy()
    {
        string who = "160.39.244.23";         // ip address of the ipad in the ad-hoc network

//		string who = "www.google.com";

        System.Net.NetworkInformation.Ping pingSender = new System.Net.NetworkInformation.Ping();

        // When the PingCompleted event is raised,
        // the PingCompletedCallback method is called.
        pingSender.PingCompleted += PingCompletedCallback;

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

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

        // Wait 12 seconds for a reply.
        int timeout = 12000;         // in milliseconds

        // Set options for transmission:
        // The data can go through 64 gateways or routers
        // before it is destroyed, and the data packet
        // cannot be fragmented.
        PingOptions options = new PingOptions(64, true);

//		Console.WriteLine("Time to live: {0}", options.Ttl);
//		Console.WriteLine("Don't fragment: {0}", options.DontFragment);

        // Send the ping asynchronously.
        // Use the waiter as the user token.
        // When the callback completes, it can wake up this thread.
        pingSender.SendAsync(who, timeout, buffer, options);

        // Prevent this example application from ending.
        // A real application should do something useful
        // when possible.
//		Debug.Log("Ping example completed.");
    }
Beispiel #38
0
        public bool Test()
        {
            AutoResetEvent waiter = new AutoResetEvent(false);

            Ping pingSender = new Ping();

            // When the PingCompleted event is raised,
            // the PingCompletedCallback method is called.
            pingSender.PingCompleted += new PingCompletedEventHandler(PingCompletedCallback);

            // Create a buffer of 32 bytes of CommandText to be transmitted.
            byte[] buffer = Encoding.ASCII.GetBytes(CommandText);

            // Wait 12 seconds for a reply.
            int timeout = 20;

            // Set options for transmission:
            // The CommandText can go through 64 gateways or routers
            // before it is destroyed, and the CommandText packet
            // cannot be fragmented.
            PingOptions options = new PingOptions(64, true);

            //Console.WriteLine("Time to live: {0}", options.Ttl);
            //Console.WriteLine("Don't fragment: {0}", options.DontFragment);

            // Send the ping asynchronously.
            // Use the waiter as the user token.
            // When the callback completes, it can wake up this thread.
            pingSender.SendAsync(ip, timeout, buffer, options, waiter.Set());

            // Prevent this example application from ending.
            // A real application should do something useful
            // when possible.
            waiter.WaitOne();
            Console.WriteLine("Ping example completed.");
            //Console.Read();
            return isPing;
        }
        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);
            SetContentView(Resource.Layout.Main);
            Button button = FindViewById<Button>(Resource.Id.MyButton);

            button.Click += delegate {
                var ping = new Ping();
                var ipaddress = UdpSocketPort.LastPacketAddress ?? IPAddress.Parse("10.71.34.1");
                var func = new Action( delegate
                {
                    button.Text = string.Format("Pong!!! {0} {1}", ipaddress.ToString(), count);
                });

                ping.SendAsync(ipaddress, func );

                button.Text = string.Format("Ping... {0} {1}", ipaddress.ToString(), count++);
                msg(button.Text);
            };

            txtHistory = FindViewById<TextView>(Resource.Id.textView2);
            txtHistory.Text = "";

            txtVoltage = FindViewById<TextView>(Resource.Id.textView1);
            txtVoltage.Text = "";

            string hostname = Dns.GetHostName();
            msg("hostname ={0}", hostname);

            IPAddress[] adrList = Dns.GetHostAddresses(hostname);
            foreach (IPAddress address in adrList)
            {
                msg("address ={0}", address.ToString());
            }

            UdpSocketPort = new UdpSocketPort(11001, 11002, this.msgfixed, this.changeVoltage);
            UdpSocketPort.Comm_Start();
        }
Beispiel #40
0
        private void button1_Click(object sender, EventArgs e)
        {
            timer1.Interval = 2000;
            for (c = 45; c <= 47; c++)
            {
                for (d = 1; d <= 255; d++)
                {
                    //ping他,返回只
                    now = rootstr + c + "." + d;
                    // textBox2.Text = now;
                    Ping myping = new Ping();
                    AutoResetEvent myreset = new AutoResetEvent(false);
                    myping.PingCompleted += new PingCompletedEventHandler(pingcom);
                    myping.SendAsync(rootstr + c + "." + d, myreset);

                    //PingReply myrep = myping.Send(now);
                    //if (myrep.Status == IPStatus.Success)
                    //{
                    //    textBox1.Text += now + "  time:" + myrep.RoundtripTime + "\r\n";
                    //}

                }
            }
        }
Beispiel #41
0
 /**
  * function to run command prompt command
  * arp -g
  * and ping all resulting IP address to check for their name
  * and activity status
  */
 public static void getIpList()
 {
     Process process = new Process();
     ProcessStartInfo startInfo = new ProcessStartInfo();
     startInfo.FileName = "arp";
     startInfo.Arguments = "-g";
     startInfo.RedirectStandardOutput = true;
     startInfo.UseShellExecute = false;
     process.StartInfo = startInfo;
     process.Start();
     String strData = process.StandardOutput.ReadToEnd();
     Regex ip = new Regex(@"\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b");
     MatchCollection result = ip.Matches(strData);
     foreach (Match r in result)
     {
         try
         {
             Ping p = new Ping();
             p.PingCompleted += new PingCompletedEventHandler(p_PingCompleted);
             p.SendAsync(r.ToString(), 100, r.ToString());
         }
         catch (Exception ex) { }
     }
 }
Beispiel #42
0
 /// <summary>
 /// Asynchronously attempts to send an Internet Control Message Protocol (ICMP) echo message.
 /// </summary>
 /// <param name="ping">The Ping.</param>
 /// <param name="address">An IPAddress that identifies the computer that is the destination for the ICMP echo message.</param>
 /// <param name="timeout">
 /// An Int32 value that specifies the maximum number of milliseconds (after sending the echo message)
 /// to wait for the ICMP echo reply message.
 /// </param>
 /// <param name="userToken">A user-defined object stored in the resulting Task.</param>
 /// <returns>A task that represents the asynchronous operation.</returns>
 public static Task <PingReply> SendTask(this Ping ping, IPAddress address, int timeout, object userToken)
 {
     return(SendTaskCore(ping, userToken, tcs => ping.SendAsync(address, timeout, tcs)));
 }
Beispiel #43
0
        private void Form1_Load(object sender, EventArgs e)
        {
            Ping pingSender = new Ping();
            int timeout = 120;
               // PingReply reply = pingSender.Send("r7878+98");
            pingSender.PingCompleted += new PingCompletedEventHandler(Pingtest);
            pingSender.SendAsync("roopermines.org", timeout);

            richTextBox1.BackColor = Color.Black;
            richTextBox1.ForeColor = Color.White;
            richTextBox1.AppendText("RSVP Update Client v.0.2");
            richTextBox1.AppendText("\nClick update to install or update rsvp modpack.");
            richTextBox1.AppendText("\nNote: Update may take a while.\n");
        }
Beispiel #44
0
        public void pingIP(string IP)
        {
            Ping pingSender = new Ping();
                PingOptions options = new PingOptions();
                AutoResetEvent waiter = new AutoResetEvent(false);
                pingSender.PingCompleted += new PingCompletedEventHandler(PingCompletedCallback);

                // Create a buffer of 32 bytes of data to be transmitted.
                string data = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
                byte[] buffer = Encoding.ASCII.GetBytes(data);
                int timeout = 1200;
                //PingReply reply = pingSender.Send(IP, timeout, buffer, options);
                pingSender.SendAsync(IP, timeout, buffer, options, waiter);
                /*
                if (reply.Status == IPStatus.Success)
                {
                    return reply.RoundtripTime;
                }
                else
                {
                    return 9999;
                }*/
        }
Beispiel #45
0
 /// <summary>
 /// Asynchronously attempts to send an Internet Control Message Protocol (ICMP) echo message.
 /// </summary>
 /// <param name="ping">The Ping.</param>
 /// <param name="hostNameOrAddress">
 /// A String that identifies the computer that is the destination for the ICMP echo message.
 /// The value specified for this parameter can be a host name or a string representation of an IP address.
 /// </param>
 /// <param name="userToken">A user-defined object stored in the resulting Task.</param>
 /// <returns>A task that represents the asynchronous operation.</returns>
 public static Task <PingReply> SendTask(this Ping ping, string hostNameOrAddress, object userToken)
 {
     return(SendTaskCore(ping, userToken, tcs => ping.SendAsync(hostNameOrAddress, tcs)));
 }
 public void Ping(string uri)
 {
     var ping = new System.Net.NetworkInformation.Ping();
     ping.PingCompleted += (_sender, pingArgs) =>
     {
         if (pingArgs.Reply != null && pingArgs.Reply.Status == IPStatus.Success)
         {
             ok = true;
         }
         else
         {
             ok = false;
             if (!alreadyRetried)
             {
                 ping.SendAsync(uri, null);//Try again
                 alreadyRetried = true;
             }
         }
         CommandManager.InvalidateRequerySuggested();
     };
     ping.SendAsync(uri, null);
 }
Beispiel #47
0
        //获取计算机列表
        private void EnumComputers()
        {
            try
            {
                for (int i = 0; i <= 255; i++)
                {
                    Ping myPing;
                    myPing = new Ping();
                    myPing.PingCompleted += new PingCompletedEventHandler(myPing_PingCompleted);

                    string pingIP = "192.168.1." + i.ToString();
                    myPing.SendAsync(pingIP, 1000, null);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
Beispiel #48
0
 /// <summary>
 /// Asynchronously attempts to send an Internet Control Message Protocol (ICMP) echo message.
 /// </summary>
 /// <param name="ping">The Ping.</param>
 /// <param name="hostNameOrAddress">
 /// A String that identifies the computer that is the destination for the ICMP echo message.
 /// The value specified for this parameter can be a host name or a string representation of an IP address.
 /// </param>
 /// <param name="timeout">
 /// An Int32 value that specifies the maximum number of milliseconds (after sending the echo message)
 /// to wait for the ICMP echo reply message.
 /// </param>
 /// <param name="userToken">A user-defined object stored in the resulting Task.</param>
 /// <returns>A task that represents the asynchronous operation.</returns>
 public static Task <PingReply> SendTask(this Ping ping, string hostNameOrAddress, int timeout, object userToken)
 {
     return(SendTaskCore(ping, userToken, delegate(TaskCompletionSource <PingReply> tcs) {
         ping.SendAsync(hostNameOrAddress, timeout, tcs);
     }));
 }
Beispiel #49
0
 /// <summary>
 /// Asynchronously attempts to send an Internet Control Message Protocol (ICMP) echo message.
 /// </summary>
 /// <param name="ping">The Ping.</param>
 /// <param name="address">An IPAddress that identifies the computer that is the destination for the ICMP echo message.</param>
 /// <param name="timeout">
 /// An Int32 value that specifies the maximum number of milliseconds (after sending the echo message)
 /// to wait for the ICMP echo reply message.
 /// </param>
 /// <param name="buffer">
 /// A Byte array that contains data to be sent with the ICMP echo message and returned
 /// in the ICMP echo reply message. The array cannot contain more than 65,500 bytes.
 /// </param>
 /// <param name="userToken">A user-defined object stored in the resulting Task.</param>
 /// <returns>A task that represents the asynchronous operation.</returns>
 public static Task <PingReply> SendTask(this Ping ping, IPAddress address, int timeout, byte[] buffer, object userToken)
 {
     return(SendTaskCore(ping, userToken, delegate(TaskCompletionSource <PingReply> tcs) {
         ping.SendAsync(address, timeout, buffer, tcs);
     }));
 }
        // FIXME this is blocked by some providers as "ICMP flood"
        // FIXME make selector between this and Unity
        private static void PingICMPAsync(ServerData ret, int pingTimeout, byte[] pingBuffer, PingOptions pingOptions)
        {
            using (var ping = new Ping())
            {
                ServerList.pings.Add(ping);

                string prefix = String.Format("[P {0}][IP:p {1}:{2}]", ret.Project, ret.IP, ret.port);

                ping.PingCompleted += (s, e) => {
                    if (e.Cancelled)
                    {
                        Console.WriteLine(String.Format(
                                              "{0} Ping was cancelled.",
                                              prefix
                                              ));

                        ((AutoResetEvent)e.UserState).Set();
                        return;
                    }

                    if (e.Error != null)
                    {
                        Console.WriteLine(String.Format(
                                              "{0} Error! {1}",
                                              prefix,
                                              e.Error.ToString()
                                              ));

                        ((AutoResetEvent)e.UserState).Set();
                        return;
                    }

                    ServerList.ProcessICMPPing(ret, pingTimeout, e.Reply);
                    ((AutoResetEvent)e.UserState).Set();
                };

                AutoResetEvent pingWaiter = new AutoResetEvent(false);
                try
                {
                    ping.SendAsync(IPAddress.Parse(ret.IP), pingTimeout, pingBuffer, pingOptions, pingWaiter);
                    return;
                }
                catch (FormatException) {
                    // server IP was probably server NS
                    // we will retry call directly
                }
                catch (SocketException e)
                {
                    Console.WriteLine(e.ToString());
                    return;
                }

                try
                {
                    ping.SendAsync(ret.IP, pingTimeout, pingBuffer, pingOptions, pingWaiter);
                    return;
                }
                catch (SocketException e)
                {
                    Console.WriteLine(e.ToString());
                    return;
                }
            }
        }
Beispiel #51
0
 // Adapted from
 // stackoverflow.com/questions/4042789/how-toget-ip-of-all-hosts-in-lan
 public static new string[] GetAdapterNames()
 {
     countdown = new CountdownEvent(1);
     List<string> networks = netBaseAddresses();
     if (!networks.Contains("192.168.0.")) { networks.Add("192.168.0."); }
     if (!networks.Contains("192.168.222.")) { networks.Add("192.168.222."); }
     foreach (string network in networks)
     {
         for (int i = 1; i < 255; i++)
         {
             string ip = String.Format("{0}{1}", network, i);
             Ping p = new Ping();
             p.PingCompleted += p_PingCompleted;
             countdown.AddCount();
             var t = Task.Factory.StartNew(() => p.SendAsync(ip, 100, ip));
             t.Wait();
         }
     }
     countdown.Signal();
     countdown.Wait();
     IPAddresses.Sort();
     return IPAddresses.ToArray();
 }
Beispiel #52
0
 internal void Send()
 {
     ts.TraceInformation("Ping: Send to {0}", this.Target);
     pingSender.SendAsyncCancel();
     pingSender.SendAsync(this.Target, (int)this.Timeout, this);
 }
 /// <summary>
 /// Asynchronously attempts to send an Internet Control Message Protocol (ICMP) echo message.
 /// </summary>
 /// <param name="ping">The Ping.</param>
 /// <param name="hostNameOrAddress">
 /// A String that identifies the computer that is the destination for the ICMP echo message.
 /// The value specified for this parameter can be a host name or a string representation of an IP address.
 /// </param>
 /// <param name="timeout">
 /// An Int32 value that specifies the maximum number of milliseconds (after sending the echo message)
 /// to wait for the ICMP echo reply message.
 /// </param>
 /// <param name="buffer">
 /// A Byte array that contains data to be sent with the ICMP echo message and returned
 /// in the ICMP echo reply message. The array cannot contain more than 65,500 bytes.
 /// </param>
 /// <param name="options">A PingOptions object used to control fragmentation and Time-to-Live values for the ICMP echo message packet.</param>
 /// <param name="userToken">A user-defined object stored in the resulting Task.</param>
 /// <returns>A task that represents the asynchronous operation.</returns>
 public static Task <PingReply> SendTask(
     this Ping ping, string hostNameOrAddress, int timeout,
     byte[] buffer, PingOptions options, object userToken) =>
 SendTaskCore(ping, userToken, tcs => ping.SendAsync(hostNameOrAddress, timeout, buffer, options, tcs));
 /// <summary>
 /// Asynchronously attempts to send an Internet Control Message Protocol (ICMP) echo message.
 /// </summary>
 /// <param name="ping">The Ping.</param>
 /// <param name="address">An IPAddress that identifies the computer that is the destination for the ICMP echo message.</param>
 /// <param name="timeout">
 /// An Int32 value that specifies the maximum number of milliseconds (after sending the echo message)
 /// to wait for the ICMP echo reply message.
 /// </param>
 /// <param name="buffer">
 /// A Byte array that contains data to be sent with the ICMP echo message and returned
 /// in the ICMP echo reply message. The array cannot contain more than 65,500 bytes.
 /// </param>
 /// <param name="userToken">A user-defined object stored in the resulting Task.</param>
 /// <returns>A task that represents the asynchronous operation.</returns>
 public static Task <PingReply> SendTask(
     this Ping ping, IPAddress address, int timeout, byte[] buffer, object userToken) =>
 SendTaskCore(ping, userToken, tcs => ping.SendAsync(address, timeout, buffer, tcs));
Beispiel #55
0
 internal static void Ping(string IP)
 {
     if (!WaitingForReply)
     {
         Ping pinger = new Ping();
         pinger.PingCompleted += new PingCompletedEventHandler(PingCompletedCallback);
         byte[] buffer = Encoding.ASCII.GetBytes("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa");
         pinger.SendAsync(IPAddress.Parse(IP), 10000, buffer, null);
     }
     WaitingForReply = true;
 }
 /// <summary>
 /// Asynchronously attempts to send an Internet Control Message Protocol (ICMP) echo message.
 /// </summary>
 /// <param name="ping">The Ping.</param>
 /// <param name="address">An IPAddress that identifies the computer that is the destination for the ICMP echo message.</param>
 /// <param name="userToken">A user-defined object stored in the resulting Task.</param>
 /// <returns>A task that represents the asynchronous operation.</returns>
 public static Task <PingReply> SendTask(this Ping ping, IPAddress address, object userToken) =>
 SendTaskCore(ping, userToken, tcs => ping.SendAsync(address, tcs));
Beispiel #57
0
        private bool scanForIPs(IPAddress vNetworkAddress, IPAddress vSubnetMask , out IPAddress[] oFoundEndpoints, out int oErrorCode)
        {
            if(!equalIPLengths(vNetworkAddress, vSubnetMask))
            {
                throw new ArgumentException("IP-Address and Subnetmask don't match in Length");
            }

            if(!IsNetworkAddress(vNetworkAddress, vSubnetMask))
            {
                throw new ArgumentException("The passed IP is no network address. Network Address is the one with the last Bits 0 ;)");
            }

            oErrorCode = 0;

            byte[] netAddressBytes = vNetworkAddress.GetAddressBytes();
            byte[] netmaskBytes = vSubnetMask.GetAddressBytes();

            foundIPs.Clear(); // New search...
            byte[] netAddr = vNetworkAddress.GetAddressBytes();

            byte[] bcAddr = GetBroadcastAddress(vNetworkAddress, vSubnetMask).GetAddressBytes();

            ulong lBCA = 0;
            ulong lNA = 0;

            for(int i=0; i<netAddr.Length; i++)
            {
                lBCA |= (ulong)((ulong)(bcAddr[i])<<(netAddr.Length-i-1)*8);
                lNA |= (ulong)((ulong)netAddr[i]<<(netAddr.Length-i-1)*8);
            }

            ulong diff = lBCA - lNA;

            IPAddress[] adresses = new IPAddress[diff-1];

            for(ulong i=1; i<diff; i++)
            {
                byte[] curAddr = new byte[netmaskBytes.Length];

                ulong lAddr = (lNA + i);

                for(int j=0; j<curAddr.Length; j++)
                {
                    ulong thisByte = lAddr >> (curAddr.Length-j-1)*8;
                    curAddr[j] = (byte)(thisByte & 0xff);
                }

                adresses[i-1] = new IPAddress(curAddr);
            }

            // Got the adresses... now start pinging threads

            pingsToDo = diff-1;
            foundIPs.Clear();

            foreach(IPAddress ip in adresses)
            {
                Ping pinger = new Ping();
                pinger.PingCompleted += new PingCompletedEventHandler(PingComplete);
                pinger.SendAsync(ip,100,ip);
            }

            while(pingsToDo > 0)
            {
                // wait, timeout set in Pings..
            }

            // Check if really Network address

            if(foundIPs.Count <= 0)
            {
                oErrorCode = -572;
                oFoundEndpoints = null;
                return(false);
            }
            IPAddress[] toReturn = new IPAddress[foundIPs.Count];

            long cnt = 0;

            foreach(IPAddress ip in foundIPs)
            {
                toReturn[cnt++] = ip;
            }
            oFoundEndpoints = toReturn;
            return true;
        }
 /// <summary>
 /// Asynchronously attempts to send an Internet Control Message Protocol (ICMP) echo message.
 /// </summary>
 /// <param name="ping">The Ping.</param>
 /// <param name="hostNameOrAddress">
 /// A String that identifies the computer that is the destination for the ICMP echo message.
 /// The value specified for this parameter can be a host name or a string representation of an IP address.
 /// </param>
 /// <param name="timeout">
 /// An Int32 value that specifies the maximum number of milliseconds (after sending the echo message)
 /// to wait for the ICMP echo reply message.
 /// </param>
 /// <param name="userToken">A user-defined object stored in the resulting Task.</param>
 /// <returns>A task that represents the asynchronous operation.</returns>
 public static Task <PingReply> SendTask(
     this Ping ping, string hostNameOrAddress, int timeout, object userToken) =>
 SendTaskCore(ping, userToken, tcs => ping.SendAsync(hostNameOrAddress, timeout, tcs));