Get local IP address of ethernet interface in C#

纵然是瞬间 提交于 2020-01-11 14:44:30

问题


Is there a reliable way to get the IPv4 address of the first local Ethernet interface in C#?

foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces())
{
    if (nic.NetworkInterfaceType == NetworkInterfaceType.Ethernet)
    {...

This finds the local IP address associated with the Ethernet adapter but also find the Npcap Loopback Adapter (installed for use with Wireshark).

Similarly, there seems to be no way to tell the difference between the loopback address and the Ethernet address using the following code:

var host = Dns.GetHostEntry(Dns.GetHostName());
foreach (var ip in host.AddressList)
{....

Any other suggestions?


回答1:


The following code gets the IPv4 from the preferred interface. This should also work inside virtual machines.

using System.Net;
using System.Net.Sockets;

public static void getIPv4()
    {
        try
        {
            using (Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, 0))
            {
                socket.Connect("10.0.1.20", 1337); // doesnt matter what it connects to
                IPEndPoint endPoint = socket.LocalEndPoint as IPEndPoint;
                Console.WriteLine(endPoint.Address.ToString()); //ipv4
            }
        }
        catch (Exception)
        {
            Console.WriteLine("Failed"); // If no connection is found
        }
    }


来源:https://stackoverflow.com/questions/37977619/get-local-ip-address-of-ethernet-interface-in-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!