在c#中使用ping

本文关键字:ping | 更新日期: 2024-10-20 01:55:04

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

在c#中使用ping

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

在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#中如何工作的简单示例。通过在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!!");
                }
            }
        }
    }
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);
         }
   });           
}
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
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();
}