Асинхронный пинг - C#
Формулировка задачи:
Пытаюсь запрограммировать асинхронный пинг, используя пример из msdn но при заполнении таблицы заполняется только первый ipaddress, остальные заполняются нулями, при этом пишется что все адреса доступны, в чем проблема?
Вот код:
byte[] cashbyte; //string ipaddres; //string host; //string status; public PingInfo() { InitializeComponent(); } private void Pingbutton_Click(object sender, EventArgs e) { if (IP1Oct1.Text != "" && IP1Oct2.Text != "" && IP1Oct3.Text != "" && IP1Oct4.Text != "" && IP2Oct1.Text != "" && IP2Oct2.Text != "" && IP2Oct3.Text != "" && IP2Oct4.Text != "") { string ipbegin = IP1Oct1.Text + "." + IP1Oct2.Text + "." + IP1Oct3.Text + "." + IP1Oct4.Text; string ipend = IP2Oct1.Text + "." + IP2Oct2.Text + "." + IP2Oct3.Text + "." + IP2Oct4.Text; IPAddress Bip = IPAddress.Parse(ipbegin); IPAddress Eip = IPAddress.Parse(ipend); byte[] bytebip = Bip.GetAddressBytes(); byte[] byteeip = Eip.GetAddressBytes(); Array.Reverse(bytebip); Array.Reverse(byteeip); uint intbip = BitConverter.ToUInt32(bytebip, 0); uint inteip = BitConverter.ToUInt32(byteeip, 0); if (inteip > intbip) { PingInfoGrid.Rows.Clear(); for (uint i = intbip; i < inteip; i++) { cashbyte = BitConverter.GetBytes(i); Array.Reverse(cashbyte); string ipaddres = new IPAddress(cashbyte).ToString(); AutoResetEvent waiter = new AutoResetEvent(false); Ping PingSender = new Ping(); PingSender.PingCompleted += new PingCompletedEventHandler(PingCompletedCallback); PingSender.SendAsync(ipaddres, waiter); //waiter.WaitOne(); } } else MessageBox.Show("Неверно задан диапазон"); } else { MessageBox.Show("Неправильный формат IP адреса!"); return; } } private void PingCompletedCallback(object sender, PingCompletedEventArgs e) { string host=""; string status=""; if (e.Error != null) { ((AutoResetEvent)e.UserState).Set(); } PingReply reply = e.Reply; if (reply.Status == IPStatus.Success) { try { host = Dns.GetHostEntry(e.Reply.Address).HostName; } catch { } finally { host = ""; } status = "Доступен"; } if (reply.Status == IPStatus.DestinationHostUnreachable) { host = ""; status = "Недоступен"; } PingInfoGrid.Rows.Add(e.Reply.Address.ToString(), host, status); ((AutoResetEvent)e.UserState).Set(); }
Насколько я понял проблема в том что основной поток завершается быстрее чем отрабатывают асинхронные пинги, но как это изменить?
Решение задачи: «Асинхронный пинг»
textual
Листинг программы
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Text; using System.Windows.Forms; using System.Net.NetworkInformation; using System.Net; using System.Threading; namespace PingProgram { public partial class PingInfo : Form { public PingInfo() { InitializeComponent(); } private void Pingbutton_Click(object sender, EventArgs e) { if (IP1Oct1.Text != "" && IP1Oct2.Text != "" && IP1Oct3.Text != "" && IP1Oct4.Text != "" && IP2Oct1.Text != "" && IP2Oct2.Text != "" && IP2Oct3.Text != "" && IP2Oct4.Text != "") { byte[] cashbyte; string ipbegin = IP1Oct1.Text + "." + IP1Oct2.Text + "." + IP1Oct3.Text + "." + IP1Oct4.Text; string ipend = IP2Oct1.Text + "." + IP2Oct2.Text + "." + IP2Oct3.Text + "." + IP2Oct4.Text; IPAddress Bip = IPAddress.Parse(ipbegin); IPAddress Eip = IPAddress.Parse(ipend); byte[] bytebip = Bip.GetAddressBytes(); byte[] byteeip = Eip.GetAddressBytes(); Array.Reverse(bytebip); Array.Reverse(byteeip); uint intbip = BitConverter.ToUInt32(bytebip, 0); uint inteip = BitConverter.ToUInt32(byteeip, 0); if (inteip >= intbip) { PingInfoGrid.Rows.Clear(); for (uint i = intbip; i <= inteip; i++) { cashbyte = BitConverter.GetBytes(i); Array.Reverse(cashbyte); string ipaddres = new IPAddress(cashbyte).ToString(); Ping PingSender = new Ping(); AutoResetEvent waiter = new AutoResetEvent(false); PingSender.PingCompleted += new PingCompletedEventHandler(PingCompletedCallback); PingSender.SendAsync(ipaddres, waiter); } } else MessageBox.Show("Неверно задан диапазон"); } else { MessageBox.Show("Неправильный формат IP адреса!"); return; } } private void PingCompletedCallback(object sender, PingCompletedEventArgs e) { if (e.Error != null) { ((AutoResetEvent)e.UserState).Set(); } PingReply reply = e.Reply; AddTableInformation(e.Reply); ((AutoResetEvent)e.UserState).Set(); } private void AddTableInformation(PingReply reply) { string host = ""; string status = ""; if (reply.Status == IPStatus.Success) { try { host = Dns.GetHostEntry(reply.Address).HostName; } catch { host = ""; } status = "Доступен"; } else { try { host = Dns.GetHostEntry(reply.Address).HostName; } catch { host = ""; } status = "Недоступен"; } lock (PingInfoGrid) { PingInfoGrid.Rows.Add(reply.Address.ToString(), host, status); PingInfoGrid.Refresh(); } } #region keypress private void IP1Oct1_KeyPress(object sender, KeyPressEventArgs e) { if (!(Char.IsDigit(e.KeyChar))) { if (e.KeyChar != (char)Keys.Back) { e.Handled = true; } } } private void IP1Oct2_KeyPress(object sender, KeyPressEventArgs e) { if (!(Char.IsDigit(e.KeyChar))) { if (e.KeyChar != (char)Keys.Back) { e.Handled = true; } } } private void IP1Oct3_KeyPress(object sender, KeyPressEventArgs e) { if (!(Char.IsDigit(e.KeyChar))) { if (e.KeyChar != (char)Keys.Back) { e.Handled = true; } } } private void IP1Oct4_KeyPress(object sender, KeyPressEventArgs e) { if (!(Char.IsDigit(e.KeyChar))) { if (e.KeyChar != (char)Keys.Back) { e.Handled = true; } } } private void IP2Oct1_KeyPress(object sender, KeyPressEventArgs e) { if (!(Char.IsDigit(e.KeyChar))) { if (e.KeyChar != (char)Keys.Back) { e.Handled = true; } } } private void IP2Oct2_KeyPress(object sender, KeyPressEventArgs e) { if (!(Char.IsDigit(e.KeyChar))) { if (e.KeyChar != (char)Keys.Back) { e.Handled = true; } } } private void IP2Oct3_KeyPress(object sender, KeyPressEventArgs e) { if (!(Char.IsDigit(e.KeyChar))) { if (e.KeyChar != (char)Keys.Back) { e.Handled = true; } } } private void IP2Oct4_KeyPress(object sender, KeyPressEventArgs e) { if (!(Char.IsDigit(e.KeyChar))) { if (e.KeyChar != (char)Keys.Back) { e.Handled = true; } } } #endregion keypress } }
ИИ поможет Вам:
- решить любую задачу по программированию
- объяснить код
- расставить комментарии в коде
- и т.д