无法ping IP地址

本文关键字:地址 IP ping 无法 | 更新日期: 2023-09-27 17:57:26

我刚刚找到了一个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();
    }

无法ping IP地址

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

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

带有

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