无法ping通IP地址

时间:2014-04-09 03:06:53

标签: c# .net ping

我刚刚找到了ping应用程序的代码,它确实ping了ip地址和域名,但是当我将它集成到父表单时,它没有ping ip地址但它确实ping了域名。任何人都能为此提供解决方案吗?代码如下。

    public FrmPing()
    {
        InitializeComponent();
    }

    private void btnPing_Click(object sender, EventArgs e)
    {
        try
        {
            int c = 3;
            IPAddress ipAddress = Dns.GetHostEntry(hostTextBox.Text).AddressList[0];

            resultsListView.Items .Clear();

            for (int i = 0; i < c; i++)
            {
                System.Net.NetworkInformation.Ping ping =
                    new System.Net.NetworkInformation.Ping();

                System.Net.NetworkInformation.PingReply pingReply =
                    ping.Send(ipAddress);

                ListViewItem result = new ListViewItem(pingReply.Address.ToString());
                result.SubItems.Add(pingReply.Buffer.Count().ToString());
                result.SubItems.Add(pingReply.RoundtripTime.ToString());
                result.SubItems.Add(pingReply.Options.Ttl.ToString());
                result.SubItems.Add(pingReply.Status.ToString());
                resultsListView.Items.Add(result);

                System.Threading.Thread.Sleep(100);
            }
        }
        catch (SocketException)
        {
            MessageBox.Show("Could not resolve host name.");
        }
        catch (PingException ex)
        {
            MessageBox.Show(ex.Message);
        }
        catch (ArgumentNullException)
        {
            MessageBox.Show("Please enter the host name or IP address to ping.");
        }

        hostTextBox.Focus();
    }

1 个答案:

答案 0 :(得分:0)

如果您想ping一个地址而不是域名,则可以更改

IPAddress ipAddress = Dns.GetHostEntry(hostTextBox.Text).AddressList[0];

IPAddress ipAddress = IPAddress.Parse("youradress");