当Ping可以';t到达主机名C#

本文关键字:主机 Ping 可以 | 更新日期: 2023-09-27 18:24:38

我正试图编写一些东西,在文本框中拾取一个输入,然后将其添加前缀,然后对两者进行ping。每次我运行脚本时,如果它找不到主机名,就会给我一个异常。有没有什么方法可以强行跳过异常,使其进入else语句?还是我错过了一些简单的东西?

public void button1_Click(object sender, EventArgs e)
{
    if (String.IsNullOrWhiteSpace(textBox1.Text))
    {
        MessageBox.Show("Please enter an asset tag number.", "Dramatic failure", MessageBoxButtons.OK, MessageBoxIcon.Warning);
    }
    else
    {
        string assetTag = textBox1.Text;
        Ping pingSender = new Ping();
        string data = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
        byte[] buffer = Encoding.ASCII.GetBytes(data);
        int timeout = 1000;
        PingOptions options = new PingOptions(64, true);
        PingReply reply = pingSender.Send("WES0" + assetTag);
        if (reply.Status == IPStatus.Success)
        {
            MessageBox.Show("The IP address is: ", "Great sucess!", MessageBoxButtons.OK, MessageBoxIcon.Warning);
        }
        else
        {
        }
    }
}

当Ping可以';t到达主机名C#

try / catch捕获exeption。类似于:

try
{
    PingReply reply = pingSender.Send(nameOrAddress);
    if (reply.Status == IPStatus.Success)
    {
        MessageBox.Show("The IP address is: ", "Great sucess!", MessageBoxButtons.OK, MessageBoxIcon.Warning);
    }
    else
    {
    }
}
catch (PingException)
{
    // Discard PingExceptions
}

Ping类抛出此异常以指示在发送Internet控制消息协议(ICMP)回显请求,一种称为由Ping类引发了一个未处理的异常。应用程序应检查PingException对象的内部异常以标识问题

如果ICMP回显由于网络、ICMP或目标错误,请求失败。对于这样的错误,Ping类返回一个带有Status属性中设置的相关IPStatus值。

请在此处查找有关PingException的更多信息。

试试这个:

public void button1_Click(object sender, EventArgs e)
{
    if (String.IsNullOrWhiteSpace(textBox1.Text))
    {
        MessageBox.Show("Please enter an asset tag number.", "Dramatic failure", MessageBoxButtons.OK, MessageBoxIcon.Warning);
    }
    else
    {
        string assetTag = textBox1.Text;
        Ping pingSender = new Ping();
        string data = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
        byte[] buffer = Encoding.ASCII.GetBytes(data);
        int timeout = 1000;
        PingOptions options = new PingOptions(64, true);
        try
        {            
            PingReply reply = pingSender.Send("WES0" + assetTag);
            if (reply.Status == IPStatus.Success)
            {
                MessageBox.Show("The IP address is: ", "Great sucess!", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
            else
            {
                MessageBox.Show("Error on ping!", "Error on ping!", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }
        catch(Exception ex)
        {
            MessageBox.Show("Error on ping:" + ex.Message, "Error on ping!", MessageBoxButtons.OK, MessageBoxIcon.Warning);
        }
    }
}