C#获取活动的NIC IPv4地址 [英] C# Get Active NIC IPv4 Address

查看:56
本文介绍了C#获取活动的NIC IPv4地址的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的计算机上有多个网卡.(由于使用了VMWare)

I have multiple network cards on my computer. (Because of VMWare)

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

How can I find the IPv4 address of the active card. I mean if I send a ping in a terminal and intercept packet in WireShark, I want the address of "Source".

我想到要检查每个网络接口,并查看GateWay是空还是空?还是可以ping 127.0.0.1并获取ping请求的IP源?但是无法实现.

I thought of checking every network interface and look if GateWay is empty or null ? Or maybe ping 127.0.0.1 and get the IP source of the ping request ? But cannot implement it.

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

For now I have this code which i found on StackOverFlow

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

但是它给了我VmWare卡的IP.但是我不知道我还能用什么. .First()".

But it gets me the IP of the VmWare card. But I don't know what else that ".First()" I could use.

推荐答案

我终于找到了一种获取真实IP的有效方法.基本上,它会查找IPv4中的所有接口(即UP),并由其决定,因为它只采用具有默认网关的接口.

I have finally found an efficient way of getting the real IP. Basically it looks for all interfaces in IPv4, that are UP and the thing that makes it decide, is it only takes the interface with a default gateway.

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

这篇关于C#获取活动的NIC IPv4地址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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