ProgramingTip

네트워크 인터페이스와 올바른 IPv4 주소는 어떻게 얻습니까?

bestdevel 2020. 12. 8. 19:19
반응형

네트워크 인터페이스와 올바른 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 주소를 얻는 방법은 무엇입니까?


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입니다.


약간의 개선 으로이 코드는 조합에 모든 인터페이스를 추가합니다.

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

그리고 그중 하나를 선택하면 코드는 인터페이스의 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());
                }
            }
        }
    }
}

참고 URL : https://stackoverflow.com/questions/9855230/how-do-i-get-the-network-interface-and-its-right-ipv4-address

반응형