C# 获取活动网卡 IPv4 地址

Key*_*rap 2 c# ip-address

我的计算机上有多个网卡。(因为VMWare)

如何找到活动卡的 IPv4 地址。我的意思是,如果我在终端中发送 ping 并在 WireShark 中拦截数据包,我需要“源”的地址。

我想检查每个网络接口并查看 GateWay 是否为空或 null ?或者也许 ping 127.0.0.1 并获取 ping 请求的 IP 源?但无法实施。

现在我有在 StackOverFlow 上找到的这段代码

 public static string GetLocalIpAddress()
        {
            var host = Dns.GetHostEntry(Dns.GetHostName());
            return host.AddressList.First(h => h.AddressFamily == AddressFamily.InterNetwork).ToString();
        }
Run Code Online (Sandbox Code Playgroud)

但它让我获得了 VmWare 卡的 IP。但我不知道我还能用什么“ .First()”。

Key*_*rap 6

我终于找到了获取真实IP的有效方法。基本上,它会查找 IPv4 中所有处于 UP 状态的接口,并做出决定,是否只采用具有默认网关的接口。

public static string GetLocalIpAddress() {
    foreach(var netI in NetworkInterface.GetAllNetworkInterfaces()) {
        if (netI.NetworkInterfaceType != NetworkInterfaceType.Wireless80211 &&
            (netI.NetworkInterfaceType != NetworkInterfaceType.Ethernet ||
                netI.OperationalStatus != OperationalStatus.Up)) continue;
        foreach(var uniIpAddrInfo in netI.GetIPProperties().UnicastAddresses.Where(x => netI.GetIPProperties().GatewayAddresses.Count > 0)) {

            if (uniIpAddrInfo.Address.AddressFamily == AddressFamily.InterNetwork &&
                uniIpAddrInfo.AddressPreferredLifetime != uint.MaxValue)
                return uniIpAddrInfo.Address.ToString();
        }
    }
    Logger.Log("You local IPv4 address couldn't be found...");
    return null;
}
Run Code Online (Sandbox Code Playgroud)

5 年后编辑:同时我找到了一种更好的获取本地 IP 地址的方法。您基本上向 Google 的 DNS 服务器(或其他任何服务器)发出 DNS 请求,然后查看您的 PC 获取的源 IP 是什么。

public static string GetLocalIp() {
    using(var socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, 0)) {
        socket.Connect("8.8.8.8", 65530);
        if (!(socket.LocalEndPoint is IPEndPoint endPoint) || endPoint.Address == null) {

            return null;
        }

        return endPoint.Address.ToString();
    }
}
Run Code Online (Sandbox Code Playgroud)