SIN@SAPPOROWORKSの覚書

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

インターフェース(MACアドレス等)の一覧取得 (C#)(F#)

自端末のインターフェースの一覧が必要な場合は、
System.Net.NetworkInformation.NetworkInterface.GetAllNetworkInterfaces()を使用して
System.Net.NetworkInformation.NetworkInterfaceの配列を取得します。

System.Net.NetworkInformation.NetworkInterfaceのプロパティには、下記のようなものがあります。
Description:インターフェイスの説明
Id:アダプタのID
Name:アダプタの名前
NetworkInterfaceType:インターフェイスの種類
OperationalStatus:接続状態
Speed:速度
SupportsMulticast:マルチキャスト受信の有効無効

NetworkInterface メンバ

C# サンプル

using System;
using System.Net.NetworkInformation;

namespace MAC_001 {
    class Program {
        static void Main(string[] args) {
            var nics = NetworkInterface.GetAllNetworkInterfaces();
            if (nics != null) {
                foreach (var a in nics) {
                    Console.WriteLine("---------------------------------------------------");
                    Console.WriteLine("名前:{0}", a.Description);
                    Console.WriteLine("タイプ:{0}", a.NetworkInterfaceType);
                    var mac = a.GetPhysicalAddress().GetAddressBytes();
                    Console.Write("物理アドレス:");
                    if (mac.Length == 6)
                        Console.WriteLine("{0:x2}-{1:x2}-{2:x2}-{3:x2}-{4:x2}-{5:x2}",
                                   mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]);
                    else
                        Console.WriteLine("");

                }
            }
            Console.WriteLine();
            Console.WriteLine("何かのキーを押してください。");
            Console.ReadKey();
        }
    }
}

F# サンプル

open System
open System.Net.NetworkInformation

let nics = NetworkInterface.GetAllNetworkInterfaces();
if nics <> null then
    for a in nics do 
        printfn "---------------------------------------------------"
        printfn "名前:%s" a.Description
        printfn "タイプ:%s" (a.NetworkInterfaceType.ToString())
        printf  "物理アドレス:"
        let mac = a.GetPhysicalAddress().GetAddressBytes()
        if mac.Length=6 then
            printfn "%02x-%02x-%02x-%02x-%02x-%02x-" mac.[0] mac.[1] mac.[2] mac.[3] mac.[4] mac.[5]
        else
            printfn ""
    printfn "何かのキーを押してください。"
    Console.ReadKey() |> ignore