web-dev-qa-db-ja.com

ネットワークインターフェイスとその正しいIPv4アドレスを取得するにはどうすればよいですか?

IPv4 アドレスですべてのネットワークインターフェイスを取得する方法を知る必要があります。 または単にワイヤレスとイーサネット。

すべてのネットワークインターフェイスの詳細を取得するには、これを使用します。

foreach (NetworkInterface ni in NetworkInterface.GetAllNetworkInterfaces()) {
    if(ni.NetworkInterfaceType == NetworkInterfaceType.Wireless80211 ||
       ni.NetworkInterfaceType == NetworkInterfaceType.Ethernet) {

        Console.WriteLine(ni.Name);
    }
}

コンピューターのホストされているすべてのIPv4アドレスを取得するには:

IPAddress [] IPS = Dns.GetHostAddresses(Dns.GetHostName());
foreach (IPAddress ip in IPS) {
    if (ip.AddressFamily == AddressFamily.InterNetwork) {

        Console.WriteLine("IP address: " + ip);
    }
}

しかし、ネットワークインターフェイスとその正しいIPv4アドレスを取得する方法は?

59
Murhaf Sousli
foreach(NetworkInterface ni in NetworkInterface.GetAllNetworkInterfaces())
{
   if(ni.NetworkInterfaceType == NetworkInterfaceType.Wireless80211 || ni.NetworkInterfaceType == NetworkInterfaceType.Ethernet)
   {
       Console.WriteLine(ni.Name);
       foreach (UnicastIPAddressInformation ip in ni.GetIPProperties().UnicastAddresses)
       {
           if (ip.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
           {
               Console.WriteLine(ip.Address.ToString());
           }
       }
   }  
}

これはあなたが欲しいものを取得する必要があります。 ip.Addressは、必要なIPAddressです。

99
bwall

いくつかの改善により、このコードは任意のインターフェースを組み合わせに追加します。

private void LanSetting_Load(object sender, EventArgs e)
{
    foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces())
    {
        if ((nic.NetworkInterfaceType == NetworkInterfaceType.Ethernet) || (nic.NetworkInterfaceType == NetworkInterfaceType.Wireless80211)) //&& (nic.OperationalStatus == OperationalStatus.Up))
        {
            comboBoxLanInternet.Items.Add(nic.Description);
        }
    }
}

そして、それらの1つを選択すると、このコードはインターフェースのIPアドレスを返します。

private void comboBoxLanInternet_SelectedIndexChanged(object sender, EventArgs e)
{
    foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces())
    {
        foreach (UnicastIPAddressInformation ip in nic.GetIPProperties().UnicastAddresses)
        {
            if (nic.Description == comboBoxLanInternet.SelectedItem.ToString())
            {
                if (ip.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
                {
                    MessageBox.Show(ip.Address.ToString());
                }
            }
        }
    }
}
1
Hady Mahmoodi