3
7

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

C#でPingしてみよう

Posted at

ネットワーク上の共有フォルダからファイルを取得したいが、事前にアクセスできるかどうかを確認してから取得したほうが例外を投げずに済むようにするには、というところで下のような感じでさくっとサンプルを書いてみました。
なお非同期的にやりたい場合はSendAsyncメソッドでTask<PingReply>を取得できます。

Ping.cs
using System;
using System.Collections.Generic;
using System.Linq;
//Pingを使用するにはこの名前空間が必要。
using System.Net.NetworkInformation;

namespace test
{
    class Program
    {
        static void Main(string[] args)
        {
            var ping = new Ping();
            var replies = new List<PingReply>();

            for (int i = 0; i < 5; i++)
            {
                //Sendメソッドでリクエストを送り、結果を格納したPingReplyクラスを返す。
                var reply = ping.Send("google.com");
                replies.Add(reply);
            }

            //Pingの返答が正しく返ってきたときはStatusプロパティでIPStatus列挙のSuccessを返す。Success以外はFalseである
            var isSucceeded = replies.Any(reply => reply.Status == IPStatus.Success);
            Console.WriteLine($"ping succeeded is {isSucceeded}");

            //時間がどれだけかかったかを知りたい場合はRoundtripTimeプロパティで取得可能
            var averageTime = replies.Average(reply => reply.RoundtripTime);
            Console.WriteLine($"ping average time is {averageTime}");


            Console.ReadLine();
        }

    }
}
3
7
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
7

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?