.NET Framework 클래스 라이브러리
Ping 클래스

업데이트: 2007년 11월

응용 프로그램에서 네트워크를 통해 원격 컴퓨터에 액세스할 수 있는지 여부를 확인하는 데 사용하는 클래스입니다.

네임스페이스:  System.Net.NetworkInformation
어셈블리:  System(System.dll)

구문

Visual Basic(선언)
Public Class Ping _
    Inherits Component _
    Implements IDisposable
Visual Basic (사용법)
Dim instance As Ping
C#
public class Ping : Component, IDisposable
Visual C++
public ref class Ping : public Component, 
    IDisposable
J#
public class Ping extends Component implements IDisposable
JScript
public class Ping extends Component implements IDisposable
설명

응용 프로그램에서는 Ping 클래스를 사용하여 원격 컴퓨터에 연결 가능한지 여부를 확인합니다.

Ping이 원격 호스트에 성공적으로 연결할 수 있는지 여부는 네트워크 토폴로지에 따라 다를 수 있습니다. 프록시, NAT(Network Address Translation) 장비 또는 방화벽이 사용되거나 구성된 경우 Ping이 실패할 수 있습니다. Ping에 성공할 경우 이는 네트워크에서 원격 호스트에 연결할 수 있다는 것만 나타내며, 원격 호스트에 웹 서버와 같은 상위 수준의 서비스가 있는지는 보장할 수 없습니다.

이 클래스는 Ping.exe 명령줄 도구와 유사한 기능을 제공합니다. SendSendAsync 메서드는 원격 컴퓨터에 ICMP(Internet Control Message Protocol) Echo Request 메시지를 보내고 해당 컴퓨터로부터의 ICMP Echo Reply 메시지를 기다립니다. ICMP 메시지에 대한 자세한 내용은 http://www.ietf.org의 RFC 792를 참조하십시오.

다음 표에서는 Ping 클래스와 함께 사용할 수 있는 형식을 보여 줍니다.

형식 이름

설명

IPStatus

ICMP Echo Request 메시지의 결과를 설명하는 상태 코드를 정의합니다.

PingOptions

요청 패킷의 전달 가능 횟수(Ttl)와 조각화 여부(DontFragment)를 제어하는 설정을 구성하거나 검색하는 데 사용할 수 있습니다.

PingReply

ICMP Echo Request의 결과가 들어 있습니다.

PingException

복구할 수 없는 오류가 발생한 경우 throw됩니다.

PingCompletedEventArgs

SendAsync 호출이 완료되거나 취소될 때 발생하는 PingCompleted 이벤트와 관련된 데이터가 들어 있습니다.

PingCompletedEventHandler

SendAsync 호출이 완료되거나 취소될 때 호출되는 콜백 메서드를 제공하는 대리자입니다.

SendSendAsync 메서드는 PingReply 개체를 사용하여 회신을 반환합니다. PingReply..::.Status 속성은 요청의 결과를 나타내는 IPStatus 값을 반환합니다.

요청을 보낼 때는 원격 컴퓨터를 지정해야 합니다. 호스트 이름 문자열, 문자열 형식의 IP 주소 또는 IPAddress 개체를 지정하여 원격 컴퓨터를 지정할 수 있습니다.

다음과 같은 정보도 지정할 수 있습니다.

  • 요청과 함께 보낼 데이터를 지정할 수 있습니다. buffer를 지정하면 특정 크기의 패킷을 원격 호스트로 보내고 받는 데 필요한 시간과 네트워크 경로의 최대 전송 단위를 알 수 있습니다. 자세한 내용은 buffer 매개 변수를 사용하는 Send 또는 SendAsync 오버로드를 참조하십시오.

  • ICMP Echo 패킷을 조각화하여 전송할 수 있는지 여부를 지정할 수 있습니다. 자세한 내용은 DontFragment 속성과, options 매개 변수를 사용하는 Send 또는 SendAsync 오버로드를 참조하십시오.

  • 패킷이 대상 컴퓨터에 도달하거나 삭제되기 전까지 라우터 또는 게이트웨이와 같은 라우팅 노드에서 패킷을 전달할 수 있는 횟수를 지정할 수 있습니다. 자세한 내용은 Ttl과, options 매개 변수를 사용하는 Send 또는 SendAsync 오버로드를 참조하십시오.

  • 회신을 받아야 하는 제한 시간을 지정할 수 있습니다. 자세한 내용은 timeout 매개 변수를 사용하는 Send 또는 SendAsync 오버로드를 참조하십시오.

Ping 클래스에서는 요청을 보내기 위한 동기 메서드와 비동기 메서드를 모두 제공합니다. 회신을 기다리는 동안 응용 프로그램을 차단해야 하는 경우에는 동기 방식의 Send 메서드를 사용합니다. 응용 프로그램을 차단하지 않아야 하는 경우에는 비동기 방식의 SendAsync 메서드를 사용합니다. SendAsync에 대한 호출은 스레드 풀에서 자동으로 할당되는 자체 스레드에서 실행됩니다. 비동기 작업이 완료되면 PingCompleted 이벤트가 발생합니다. 응용 프로그램에서는 PingCompletedEventHandler 대리자를 사용하여 PingCompleted 이벤트가 발생할 경우 호출되는 메서드를 지정합니다. SendAsync를 호출하기 전에 PingCompletedEventHandler 대리자를 이벤트에 추가해야 합니다. 대리자의 메서드는 SendAsync 호출의 결과를 설명하는 PingReply 개체가 포함된 PingCompletedEventArgs 개체를 받습니다.

Ping 클래스의 동일한 인스턴스를 사용하여 ICMP Echo Request를 동시에 여러 개 생성할 수 없습니다. SendAsync 호출이 진행 중일 때 Send를 호출하거나 이전의 모든 호출이 완료되기 전에 SendAsync를 여러 번 호출하면 InvalidOperationException이 발생합니다.

예제

다음 코드 예제에서는 Ping 클래스를 동기적으로 사용하는 방법을 보여 줍니다.

C#
using System;
using System.Net;
using System.Net.NetworkInformation;
using System.Text;

namespace Examples.System.Net.NetworkInformation.PingTest
{
    public class PingExample
    {
        // args[0] can be an IPaddress or host name.
        public static void Main (string[] args)
        {
            Ping pingSender = new Ping ();
            PingOptions options = new PingOptions ();

            // Use the default Ttl value which is 128,
            // but change the fragmentation behavior.
            options.DontFragment = true;

            // Create a buffer of 32 bytes of data to be transmitted.
            string data = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
            byte[] buffer = Encoding.ASCII.GetBytes (data);
            int timeout = 120;
            PingReply reply = pingSender.Send (args[0], timeout, buffer, options);
            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);
            }
        }
    }
}
Visual C++
#using <System.dll>

using namespace System;
using namespace System::Net;
using namespace System::Net::NetworkInformation;
using namespace System::Text;

// args[1] can be an IPaddress or host name.
int main()
{
   array<String^>^args = Environment::GetCommandLineArgs();

   Ping ^ pingSender = gcnew Ping;
   PingOptions ^ options = gcnew PingOptions;

   // Use the default Ttl value which is 128,
   // but change the fragmentation behavior.
   options->DontFragment = true;

   // Create a buffer of 32 bytes of data to be transmitted.
   String^ data = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
   array<Byte>^buffer = Encoding::ASCII->GetBytes( data );
   int timeout = 120;
   PingReply ^ reply = pingSender->Send( args[ 1 ], timeout, buffer, options );

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


}

다음 코드 예제에서는 Ping 클래스를 비동기적으로 사용하는 방법을 보여 줍니다.

C#
using System;
using System.Text;
using System.Net;
using System.Net.NetworkInformation;
using System.ComponentModel;
using System.Threading;

namespace Examples.System.Net.NetworkInformation.PingTest
{
    public class PingExample
    {
        public static void Main (string[] args)
        {
            if (args.Length == 0)
                throw new ArgumentException ("Ping needs a host or IP Address.");

            string who = args[0];
            AutoResetEvent waiter = new AutoResetEvent (false);

            Ping pingSender = new Ping ();

            // When the PingCompleted event is raised,
            // the PingCompletedCallback method is called.
            pingSender.PingCompleted += new PingCompletedEventHandler (PingCompletedCallback);

            // Create a buffer of 32 bytes of data to be transmitted.
            string data = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
            byte[] buffer = Encoding.ASCII.GetBytes (data);

            // Wait 12 seconds for a reply.
            int timeout = 12000;

            // Set options for transmission:
            // The data can go through 64 gateways or routers
            // before it is destroyed, and the data packet
            // cannot be fragmented.
            PingOptions options = new PingOptions (64, true);

            Console.WriteLine ("Time to live: {0}", options.Ttl);
            Console.WriteLine ("Don't fragment: {0}", options.DontFragment);

            // Send the ping asynchronously.
            // Use the waiter as the user token.
            // When the callback completes, it can wake up this thread.
            pingSender.SendAsync(who, timeout, buffer, options, waiter);

            // Prevent this example application from ending.
            // A real application should do something useful
            // when possible.
            waiter.WaitOne ();
            Console.WriteLine ("Ping example completed.");
        }

        private static void PingCompletedCallback (object sender, PingCompletedEventArgs e)
        {
            // If the operation was canceled, display a message to the user.
            if (e.Cancelled)
            {
                Console.WriteLine ("Ping canceled.");

                // Let the main thread resume. 
                // UserToken is the AutoResetEvent object that the main thread 
                // is waiting for.
                ((AutoResetEvent)e.UserState).Set ();
            }

            // If an error occurred, display the exception to the user.
            if (e.Error != null)
            {
                Console.WriteLine ("Ping failed:");
                Console.WriteLine (e.Error.ToString ());

                // Let the main thread resume. 
                ((AutoResetEvent)e.UserState).Set();
            }

            PingReply reply = e.Reply;

            DisplayReply (reply);

            // Let the main thread resume.
            ((AutoResetEvent)e.UserState).Set();
        }

        public static void DisplayReply (PingReply reply)
        {
            if (reply == null)
                return;

            Console.WriteLine ("ping status: {0}", reply.Status);
            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);
            }
        }
    }
}
Visual C++
#using <System.dll>

using namespace System;
using namespace System::Text;
using namespace System::Net;
using namespace System::Net::NetworkInformation;
using namespace System::ComponentModel;
using namespace System::Threading;
void PingCompletedCallback( Object^ sender, PingCompletedEventArgs^ e );
void DisplayReply( PingReply^ reply );
int main()
{
   array<String^>^args = Environment::GetCommandLineArgs();
   if ( args->Length == 1 )
      throw gcnew ArgumentException( "Ping needs a host or IP Address." );

   String^ who = args[ 1 ];
   AutoResetEvent^ waiter = gcnew AutoResetEvent( false );

   Ping ^ pingSender = gcnew Ping;

   // When the PingCompleted event is raised,
   // the PingCompletedCallback method is called.
   pingSender->PingCompleted += gcnew PingCompletedEventHandler( PingCompletedCallback );

   // Create a buffer of 32 bytes of data to be transmitted.
   String^ data = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
   array<Byte>^buffer = Encoding::ASCII->GetBytes( data );

   // Wait 12 seconds for a reply.
   int timeout = 12000;

   // Set options for transmission:
   // The data can go through 64 gateways or routers
   // before it is destroyed, and the data packet
   // cannot be fragmented.
   PingOptions ^ options = gcnew PingOptions( 64,true );
   Console::WriteLine( "Time to live: {0}", options->Ttl );
   Console::WriteLine( "Don't fragment: {0}", options->DontFragment );

   // Send the ping asynchronously.
   // Use the waiter as the user token.
   // When the callback completes, it can wake up this thread.
   pingSender->SendAsync( who, timeout, buffer, options, waiter );

   // Prevent this example application from ending.
   // A real application should do something useful
   // when possible.
   waiter->WaitOne();
   Console::WriteLine( "Ping example completed." );
}


void PingCompletedCallback( Object^ /*sender*/, PingCompletedEventArgs^ e )
{

   // If the operation was canceled, display a message to the user.
   if ( e->Cancelled )
   {
      Console::WriteLine( "Ping canceled." );

      // Let the main thread resume. 
      // UserToken is the AutoResetEvent object that the main thread 
      // is waiting for.
      (dynamic_cast<AutoResetEvent^>(e->UserState))->Set();
   }


   // If an error occurred, display the exception to the user.
   if ( e->Error != nullptr )
   {
      Console::WriteLine( "Ping failed:" );
      Console::WriteLine( e->Error->ToString() );

      // Let the main thread resume. 
      (dynamic_cast<AutoResetEvent^>(e->UserState))->Set();
   }

   PingReply ^ reply = e->Reply;
   DisplayReply( reply );

   // Let the main thread resume.
   (dynamic_cast<AutoResetEvent^>(e->UserState))->Set();
}


void DisplayReply( PingReply ^ reply )
{
   if ( reply == nullptr )
      return;

   Console::WriteLine( "ping status: {0}", reply->Status );
   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 );
   }
}

상속 계층 구조

System..::.Object
  System..::.MarshalByRefObject
    System.ComponentModel..::.Component
      System.Net.NetworkInformation..::.Ping
스레드로부터의 안전성

이 형식의 모든 공용 static(Visual Basic의 경우 Shared) 멤버는 스레드로부터 안전합니다. 인터페이스 멤버는 스레드로부터 안전하지 않습니다.
플랫폼

Windows Vista, Windows XP SP2, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP Starter Edition, Windows Server 2003, Windows Server 2000 SP4, Windows Millennium Edition, Windows 98

.NET Framework 및 .NET Compact Framework에서 모든 플랫폼의 전체 버전을 지원하지는 않습니다. 지원되는 버전의 목록을 보려면 .NET Framework 시스템 요구 사항을 참조하십시오.

버전 정보

.NET Framework

3.5, 3.0, 2.0에서 지원
참고 항목

참조

태그 :


Page view tracker