在C#中获取以太网接口的本地IP地址

Get local IP address of ethernet interface in C#

在 C# 中是否有可靠的方法来获取第一个本地以太网接口的 IPv4 地址?

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

这会找到与以太网适配器关联的本地 IP 地址,还会找到 Npcap 环回适配器(安装用于 Wireshark)。

同样,似乎没有办法使用以下代码区分环回地址和以太网地址:

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

还有其他建议吗?

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