101

当我用 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");
}
4

5 回答 5

241
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;
}
于 2012-08-03T23:08:51.760 回答
45

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

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

以下是一个简单的示例,WinForms用于演示 ping 在 c# 中的工作原理。通过在 中提供一个有效的 IP 地址textBox1并单击button1,我们将创建一个Ping类的实例、一个局部变量PingReply和一个用于存储 IP 或 URL 地址的字符串。我们分配PingReply给 pingSend方法,然后通过比较回复的状态和属性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!!");
                }
            }
        }
    }
于 2014-10-17T20:08:30.297 回答
2
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
于 2020-05-31T15:04:20.050 回答
0
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);
         }
   });           
}
于 2021-01-24T09:17:40.820 回答
-11
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();
}
于 2016-11-03T19:51:39.783 回答