我的电脑上有多个网卡。(因为VMWare(
如何找到活动卡的 IPv4 地址。我的意思是,如果我在终端中发送ping并在WireShark中拦截数据包,我想要"源"的地址。
我想检查每个网络接口,看看 GateWay 是空的还是空的?或者也许 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();
}
但它让我获得了VmWare卡的IP。但我不知道我还能用什么".First()
"。
我终于找到了一种获得真实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;
}
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();
}
}
好吧,我的朋友,你可以执行以下操作:
var nics = NetworkInterface.GetAllNetworkInterfaces();
foreach (var networkInterface in nics)
{
if (networkInterface.OperationalStatus == OperationalStatus.Up)
{
var address = networkInterface.GetPhysicalAddress();
}
}
地址变量允许您访问当前向上网络接口的物理地址