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

时间:2016-06-22 20:25:01

标签: c# ip ethernet loopback

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

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

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

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

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

还有其他建议吗?

1 个答案:

答案 0 :(得分:2)

  

以下代码从首选界面获取IPv4。这也适用于虚拟机。

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