How do I get the network interface and its right IPv4 address?

后端 未结 3 868
悲哀的现实
悲哀的现实 2020-11-27 14:42

I need to know how to get all network interfaces with their IPv4 address. Or just wireless and Ethernet.

To get all network interfaces details I use this:

相关标签:
3条回答
  • 2020-11-27 15:24

    One line with Lamda:

    using System.Collections.Generic;
    using System.Linq;
    using System.Net;
    using System.Net.Sockets;
    using System.Net.NetworkInformation;
    
    var ipV4s = NetworkInterface.GetAllNetworkInterfaces()
        .Select(i => i.GetIPProperties().UnicastAddresses)
        .SelectMany(u => u)
        .Where(u => u.Address.AddressFamily == AddressFamily.InterNetwork)
        .Select(i => i.Address);
    
    0 讨论(0)
  • 2020-11-27 15:26
    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());
               }
           }
       }  
    }
    

    This should get you what you want. ip.Address is an IPAddress, that you want.

    0 讨论(0)
  • 2020-11-27 15:36

    With some improvement, this code adds any interface to a combination:

    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);
            }
        }
    }
    

    And when selecting one of them, this code returns the IP address of the interface:

    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());
                    }
                }
            }
        }
    }
    
    0 讨论(0)
提交回复
热议问题