SIN@SAPPOROWORKSの覚書

C#を中心に、夜な夜な試行錯誤したコードの記録です。

パケットの送受信量 (C#)(F#)

System.Net.NetworkInformation.NetworkInterface.GetAllNetworkInterfaces()でパケットの送受信量を取得することができます。

サンプルでは、キーを押すたびに最新の情報を再表示します。

C#サンプル

using System;
using System.Net.NetworkInformation;

namespace Example {
    class Program {
        static void Main(string[] args) {
            var ni = NetworkInterface.GetAllNetworkInterfaces();
            while (true) {
                Console.WriteLine("{0,-45}\t{1,10}\t{2,10}", "Description","Recv","Send");
                Console.WriteLine("-------------------------------------------------------------------------");
                foreach (var n in ni) {
                    var s = n.GetIPv4Statistics();
                    Console.WriteLine("{0,-45}\t{1,10}\t{2,10}", n.Description,s.BytesReceived, s.BytesSent);
                }
                Console.WriteLine("");
                Console.WriteLine("何かのキーを押すと更新されます(Xで終了)");
                var k = Console.ReadKey();
                if (k.Key == ConsoleKey.X)
                    break;
                Console.Clear();
            }
        }
    }
}

F#サンプル
F#のwhileにbreakが無いのを知って愕然とした。
whileの部分、もう少し何とかならないものだろうか・・・

open System
open System.Net.NetworkInformation

let ar = 
    NetworkInterface.GetAllNetworkInterfaces()
    |>Seq.map(fun n -> n,n.GetIPv4Statistics())
    |>Seq.map(fun (n,s) -> n.Description,s.BytesReceived,s.BytesSent)

let mutable key = ConsoleKey.A
while key <> ConsoleKey.X do
    printfn "%-45s\t%-10s\t%-10s" "Description" "Recv" "Send"
    printfn "-------------------------------------------------------------------------"
    ar|>Seq.iter(fun (d,r,s) -> printfn "%-15s\t%10d\t%10d" d r s)
    
    printfn ""
    printfn "何かのキーを押すと更新されます(Xで終了)"
    key <- Console.ReadKey().Key
    Console.Clear()
done        


@zecl氏による記事
パケットの送受信量(F#) - ループとbreak - Bug Catharsis パケットの送受信量(F#) - ループとbreak - Bug Catharsis