pingの送受信 (C#)(F#)
pingの送受信は、System.Net.NetworkInformation.Pingが使用できます。
宛先にはホスト名でもIPアドレス指定可能できます。
名前解決に失敗すると例外が発生するので、ホスト名で宛先を指定する時は例外処理が必要です。
※IPv6アドレスでも使用可能ですが、Reply.Options.Ttlには値が設定されないので注意が必要です。
C#サンプル
using System.Text; using System.Net; using System.Net.NetworkInformation; namespace Example{ class Program { static void Main(string[] args) { var hostname = "www.sapporoworks.ne.jp"; var timeout = 3; var buf = new byte[32]; var ping = new Ping(); var reply = ping.Send(hostname, timeout, buf); if (reply.Status == IPStatus.Success) { Console.WriteLine("{0}からの応答: バイト数={1} 時間={2}ms TTL={3}", reply.Address, reply.Buffer.Length, reply.RoundtripTime, reply.Options.Ttl); } else { Console.WriteLine(reply.Status); } Console.WriteLine(""); Console.WriteLine("何かのキーを押してください。"); Console.ReadKey(); } } }
F#サンプル
open System open System.Text open System.Net open System.Net.NetworkInformation let hostname = "www.sapporoworks.ne.jp" let timeout = 3 let buf : byte array = Array.create 32 0uy let ping = new Ping() let reply = ping.Send(hostname, timeout, buf) if reply.Status = IPStatus.Success then printfn "%sからの応答: バイト数=%d 時間=%dms TTL=%d" (reply.Address.ToString()) reply.Buffer.Length reply.RoundtripTime reply.Options.Ttl else printfn "%s" (reply.Status.ToString()) printfn "" printfn "何かのキーを押してください。" Console.ReadKey() |> ignore