在C#中获取以太网接口的本地IP地址 [英] Get local IP address of ethernet interface in C#

查看:1200
本文介绍了在C#中获取以太网接口的本地IP地址的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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)
    {...

这会找到与以太网适配器关联的本地IP地址,还会找到Npcap环回适配器(已安装为与Wireshark一起使用).

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)
{....

还有其他建议吗?

推荐答案

以下代码从首选接口获取IPv4.这也应该在虚拟机中起作用.

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

这篇关于在C#中获取以太网接口的本地IP地址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆