如何在C#中发送ping参数

时间:2012-10-08 17:38:00

标签: c# console-application

  

可能重复:
  How to get my own IP address in C#?

在C#console应用程序中,我正在使用此代码

var ping = new Ping();
var reply = ping.Send();
if (reply.Status == IPStatus.Success)
{
    Console.WriteLine("Pinging with server");
    Console.WriteLine("Press any key to continue");
    Console.ReadKey(true);
}

所以在var reply = ping.Send();我需要传递什么参数,因为它应该写出本地机器的IP?这里我需要参数中本地机器的IP。

2 个答案:

答案 0 :(得分:1)

此代码执行此操作:

using System;
using System.Net;
using System.Net.NetworkInformation;

namespace ConsoleApplication6
{
    class Program
    {
        static void Main(string[] args)
        {
            using(var ping = new Ping())
            { 
                var reply = ping.Send(IPAddress.Loopback);

                if (reply.Status == IPStatus.Success)
                {
                    Console.WriteLine("Pinging with server: " + reply.Address);
                    Console.WriteLine("Press any key to continue");
                    Console.ReadKey(true);
                }
            }
        }
    }
}

答案 1 :(得分:0)

您可以通过以下方式进行操作:

 IPAddress add = IPAddress.Loopback; /// Reuturns local Ip Address
 PingReply reply = ping.Send(add);
 if (reply.Status == IPStatus.Success)
 {
    Console.WriteLine("Pinging with server");
    Console.WriteLine("Press any key to continue");
    Console.ReadKey(true);
  }