C# 获取活动 NIC IPv4 地址
C# Get Active NIC IPv4 Address
我的电脑上有多个网卡。 (因为 VMWare)
如何找到活动网卡的IPv4地址。我的意思是,如果我在终端中发送 ping 并在 WireShark 中拦截数据包,我想要 "Source".
的地址
我想检查每个网络接口并查看 GateWay 是否为空或 null?或者 ping 127.0.0.1 并获取 ping 请求的 IP 源?但是无法实现。
现在我有这段代码,是在 Whosebug 上找到的
public static string GetLocalIpAddress()
{
var host = Dns.GetHostEntry(Dns.GetHostName());
return host.AddressList.First(h => h.AddressFamily == AddressFamily.InterNetwork).ToString();
}
但是它让我得到了 VmWare 卡的 IP。但我不知道“.First()
”还能用什么。
好吧,我的朋友,你可以这样做:
var nics = NetworkInterface.GetAllNetworkInterfaces();
foreach (var networkInterface in nics)
{
if (networkInterface.OperationalStatus == OperationalStatus.Up)
{
var address = networkInterface.GetPhysicalAddress();
}
}
地址变量使您可以访问当前 Up 网络接口的物理地址
我终于找到了一种获取真实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;
}
我的电脑上有多个网卡。 (因为 VMWare)
如何找到活动网卡的IPv4地址。我的意思是,如果我在终端中发送 ping 并在 WireShark 中拦截数据包,我想要 "Source".
的地址我想检查每个网络接口并查看 GateWay 是否为空或 null?或者 ping 127.0.0.1 并获取 ping 请求的 IP 源?但是无法实现。
现在我有这段代码,是在 Whosebug 上找到的
public static string GetLocalIpAddress()
{
var host = Dns.GetHostEntry(Dns.GetHostName());
return host.AddressList.First(h => h.AddressFamily == AddressFamily.InterNetwork).ToString();
}
但是它让我得到了 VmWare 卡的 IP。但我不知道“.First()
”还能用什么。
好吧,我的朋友,你可以这样做:
var nics = NetworkInterface.GetAllNetworkInterfaces();
foreach (var networkInterface in nics)
{
if (networkInterface.OperationalStatus == OperationalStatus.Up)
{
var address = networkInterface.GetPhysicalAddress();
}
}
地址变量使您可以访问当前 Up 网络接口的物理地址
我终于找到了一种获取真实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;
}