【问题标题】:Using ping in c#在 C# 中使用 ping
【发布时间】:2012-08-03 18:02:07
【问题描述】:

当我用 windows ping 远程系统时,它说没有回复,但是当我用 c# ping 时,它说成功。 Windows 是正确的,设备未连接。为什么我的代码在 Windows 不通的情况下能够成功 ping?

这是我的代码:

Ping p1 = new Ping();
PingReply PR = p1.Send("192.168.2.18");
// check when the ping is not success
while (!PR.Status.ToString().Equals("Success"))
{
    Console.WriteLine(PR.Status.ToString());
    PR = p1.Send("192.168.2.18");
}
// check after the ping is n success
while (PR.Status.ToString().Equals("Success"))
{
    Console.WriteLine(PR.Status.ToString());
    PR = p1.Send("192.168.2.18");
}

【问题讨论】:

  • 当您点击 MSDN 链接 msdn.microsoft.com/en-us/library/…stackoverflow.com/questions/1281176/… 时,查看此页面底部发布的以下示例
  • 您应该将 PR.Status 与 IPStatus.Success 进行比较。在这种情况下,字符串比较不是正确的工具。
  • 执行 ping 操作后,一些 PingReply 属性的值是多少(如 PR.AddressPR.RoundtripTimePR.reply.Buffer.LengthPR.Options.Ttl)?另外你确定你的代码中有正确的 IP 地址,而不是测试 IP 地址吗?
  • Jon Senchyna :我没有设置它们,是的,我确定我的 IP 是正确的。
  • 在我的情况下,如果禁用“启用 Visual Studio 托管进程”(位置 ==>>project-> property->debug),则 ping 方法可能不起作用。请尝试!

标签: c# ping


【解决方案1】:
using System.Net.NetworkInformation;    

public static bool PingHost(string nameOrAddress)
{
    bool pingable = false;
    Ping pinger = null;

    try
    {
        pinger = new Ping();
        PingReply reply = pinger.Send(nameOrAddress);
        pingable = reply.Status == IPStatus.Success;
    }
    catch (PingException)
    {
        // Discard PingExceptions and return false;
    }
    finally
    {
        if (pinger != null)
        {
            pinger.Dispose();
        }
    }

    return pingable;
}

【讨论】:

  • 这是一个仅代码答案。我猜它实现了正确的比较并显示了如何处理可能的异常。您能否指出为什么与问题中的代码相比,这是正确的代码?
  • 不知道有多少人通过复制和粘贴来使用这个答案:/ 至少做一个using (var pinger = new Ping()) { .. } 并且早期回报如此邪恶吗?
  • 如果正确使用了 try/catch/finally,那么使用 using 包装 Ping 实例是没有意义的。这是一个或另一个,而不是两者。见stackoverflow.com/questions/278902/…
  • @JamieSee 虽然这可能是对的,但使用using 更简洁,并且在这种情况下是首选。
  • 我个人同意使用 using 语句,但您仍然必须捕获任何异常。
【解决方案2】:

在 C# 中使用 ping 是通过使用方法 Ping.Send(System.Net.IPAddress) 实现的,该方法对提供的(有效)IP 地址或 URL 运行 ping 请求并获得称为 Internet Control Message Protocol (ICMP) Packet 的响应。该数据包包含一个 20 字节的标头,其中包含来自接收到 ping 请求的服务器的响应数据。 .Net 框架System.Net.NetworkInformation 命名空间包含一个名为PingReply 的类,该类具有旨在转换ICMP 响应并提供有关被ping 服务器的有用信息的属性,例如:

  • IPStatus:获取发送互联网的主机地址 控制消息协议 (ICMP) 回显回复。
  • IPAddress:获取发送 Internet 所需的毫秒数 控制消息协议 (ICMP) 回显请求并接收 对应的 ICMP echo 回复消息。
  • RoundtripTime (System.Int64):获取用于将回复传输到 Internet 控制消息协议 (ICMP) 回显的选项 请求。
  • PingOptions (System.Byte[]):获取在 Internet 控制消息协议 (ICMP) 回显回复消息中接收到的数据缓冲区。

下面是一个简单的例子,使用WinForms 来演示 ping 在 c# 中的工作原理。通过在textBox1 中提供一个有效的IP 地址并单击button1,我们将创建一个Ping 类的实例、一个局部变量PingReply,以及一个用于存储IP 或URL 地址的字符串。我们将PingReply 分配给ping Send 方法,然后我们通过比较回复的状态与属性IPAddress.Success 状态来检查请求是否成功。最后,我们从PingReply中提取出我们需要展示给用户的信息,如上所述。

    using System;
    using System.Net.NetworkInformation;
    using System.Windows.Forms;

    namespace PingTest1
    {
        public partial class Form1 : Form
        {
            public Form1()
            {
                InitializeComponent();
            }

            private void button1_Click(object sender, EventArgs e)
            {
                Ping p = new Ping();
                PingReply r;
                string s;
                s = textBox1.Text;
                r = p.Send(s);

                if (r.Status == IPStatus.Success)
                {
                    lblResult.Text = "Ping to " + s.ToString() + "[" + r.Address.ToString() + "]" + " Successful"
                       + " Response delay = " + r.RoundtripTime.ToString() + " ms" + "\n";
                }
            }

            private void textBox1_Validated(object sender, EventArgs e)
            {
                if (string.IsNullOrWhiteSpace(textBox1.Text) || textBox1.Text == "")
                {
                    MessageBox.Show("Please use valid IP or web address!!");
                }
            }
        }
    }

【讨论】:

  • 感谢您提供使用参考!
  • 你就不能写几行解释一下你的代码吗?因为这对想要理解这段代码的人没有用......
  • 当然@Hille,几年前我很快写了这个答案,我将编辑并添加适当的答案描述。
  • Ping 使用后应该被丢弃 using (Ping p = new Ping()) { ... }
【解决方案3】:
Imports System.Net.NetworkInformation


Public Function PingHost(ByVal nameOrAddress As String) As Boolean
    Dim pingable As Boolean = False
    Dim pinger As Ping
    Dim lPingReply As PingReply

    Try
        pinger = New Ping()
        lPingReply = pinger.Send(nameOrAddress)
        MessageBox.Show(lPingReply.Status)
        If lPingReply.Status = IPStatus.Success Then

            pingable = True
        Else
            pingable = False
        End If


    Catch PingException As Exception
        pingable = False
    End Try
    Return pingable
End Function

【讨论】:

  • 这段代码是 Visual Basic 的,问题是针对 C# 的。
【解决方案4】:
private async void Ping_Click(object sender, RoutedEventArgs e)
{
    Ping pingSender = new Ping();
    string host = @"stackoverflow.com";
    await Task.Run(() =>{
         PingReply reply = pingSender.Send(host);
         if (reply.Status == IPStatus.Success)
         {
            Console.WriteLine("Address: {0}", reply.Address.ToString());
            Console.WriteLine("RoundTrip time: {0}", reply.RoundtripTime);
            Console.WriteLine("Time to live: {0}", reply.Options.Ttl);
            Console.WriteLine("Don't fragment: {0}", reply.Options.DontFragment);
            Console.WriteLine("Buffer size: {0}", reply.Buffer.Length);
         }
         else
         {
            Console.WriteLine("Address: {0}", reply.Status);
         }
   });           
}

【讨论】:

    【解决方案5】:
    private void button26_Click(object sender, EventArgs e)
    {
        System.Diagnostics.ProcessStartInfo proc = new System.Diagnostics.ProcessStartInfo();
        proc.FileName = @"C:\windows\system32\cmd.exe";
        proc.Arguments = "/c ping -t " + tx1.Text + " ";
        System.Diagnostics.Process.Start(proc);
        tx1.Focus();
    }
    
    private void button27_Click(object sender, EventArgs e)
    {
        System.Diagnostics.ProcessStartInfo proc = new System.Diagnostics.ProcessStartInfo();
        proc.FileName = @"C:\windows\system32\cmd.exe";
        proc.Arguments = "/c ping  " + tx2.Text + " ";
        System.Diagnostics.Process.Start(proc);
        tx2.Focus();
    }
    

    【讨论】:

    • 你就不能写几行解释你的代码吗?因为这对想要理解这段代码的人没有用......
    • 原来给出的代码是not DRY at all
    猜你喜欢
    • 1970-01-01
    • 2018-08-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多