LoginSignup
1
0

C# ネットワークアダプタのプロパティの取得や設定

Posted at

C# でネットワークアダプタ関連の情報を取得したり、設定する方法について説明します。

Win32_NetworkAdapterConfiguration に関する情報は多いのですが、MSFT_NetAdapter, MSFT_NetIPInterface などの MSFT_XXXX の情報が少ないので説明しますね。

WMI(Windows Management Instruction) を使うと、ネットワークアダプタの情報取得や値の設定が可能です。

プロパティの取得

下記は、ネットワークアダプタのインタフェースメトリックを取得する例です。

public uint GetNetworkInterfaceMetric(int ifIndex)
        {
            SelectQuery query = new SelectQuery("MSFT_NetIPInterface", $"InterfaceIndex={ifIndex}");
            ManagementScope scope = new ManagementScope("\\root\\StandardCimv2");
            ManagementObjectSearcher searcher = new ManagementObjectSearcher(scope, query);

            foreach (ManagementObject m in searcher.Get())
            {
                return (uint)m["InterfaceMetric"];
            }
            return uint.MinValue;
        }

プロパティの設定

例は、ネットワークアダプタのインターフェースメトリックを設定する方法です。

プロパティは、リードオンリーなプロパティと、リードライト可能なプロパティがあります。

InterfaceMetric プロパティは、リードライト可能なプロパティですので、ManagementObject の Put メソッドを利用することで値を変更することができます。

public bool SetNetworkInterfaceMetric(int ifIndex, uint metric)
       {
           SelectQuery query = new SelectQuery("MSFT_NetIPInterface", $"InterfaceIndex = {ifIndex}");
           ManagementScope scope = new ManagementScope("\\root\\StandardCimv2");
           ManagementObjectSearcher searcher = new ManagementObjectSearcher(scope, query);

           foreach (ManagementObject m in searcher.Get())
           {
               m["InterfaceMetric"] = metric;
               m.Put();    // オブジェクトへの変更をコミットする
               return true;
           }
           return false;
       }

1
0
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
1
0