在 C# 中使用 ping

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11800958/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 19:18:41  来源:igfitidea点击:

Using ping in c#

c#ping

提问by Black Star

When I Ping a remote system with windows it says there is no reply, but when I ping with c# it says success. Windows is correct, the device is not connected. Why is my code able to successfully ping when Windows is not?

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

Here is my code :

这是我的代码:

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");
}

回答by JamieSee

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;
}

回答by Ashraf Abusada

Using ping in C# is achieved by using the method Ping.Send(System.Net.IPAddress), which runs a ping request to the provided (valid) IP address or URL and gets a response which is called an Internet Control Message Protocol (ICMP) Packet. The packet contains a header of 20 bytes which contains the response data from the server which received the ping request. The .Net framework System.Net.NetworkInformationnamespace contains a class called PingReplythat has properties designed to translate the ICMPresponse and deliver useful information about the pinged server such as:

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

  • IPStatus: Gets the address of the host that sends the Internet Control Message Protocol (ICMP) echo reply.
  • IPAddress: Gets the number of milliseconds taken to send an Internet Control Message Protocol (ICMP) echo request and receive the corresponding ICMP echo reply message.
  • RoundtripTime(System.Int64): Gets the options used to transmit the reply to an Internet Control Message Protocol (ICMP) echo request.
  • PingOptions(System.Byte[]): Gets the buffer of data received in an Internet Control Message Protocol (ICMP) echo reply message.
  • IPStatus:获取发送 Internet 控制消息协议 (ICMP) 回显回复的主机的地址。
  • IPAddress:获取发送 Internet 控制消息协议 (ICMP) 回显请求并接收相应的 ICMP 回显回复消息所花费的毫秒数。
  • RoundtripTime (System.Int64):获取用于将回复传输到 Internet 控制消息协议 (ICMP) 回显请求的选项。
  • PingOptions (System.Byte[]):获取在 Internet 控制消息协议 (ICMP) 回显回复消息中接收的数据缓冲区。

The following is a simple example using WinFormsto demonstrate how ping works in c#. By providing a valid IP address in textBox1and clicking button1, we are creating an instance of the Pingclass, a local variable PingReply, and a string to store the IP or URL address. We assign PingReplyto the ping Sendmethod, then we inspect if the request was successful by comparing the status of the reply to the property IPAddress.Successstatus. Finally, we extract from PingReplythe information we need to display for the user, which is described above.

下面是一个简单的例子,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!!");
                }
            }
        }
    }

回答by Mr.Mayar

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();
}