我需要知道如何使用他们的 IPv4 获取所有网络接口(interface)地址。 或者只是无线和以太网。
要获取所有网络接口(interface)的详细信息,我使用这个:
foreach (NetworkInterface ni in NetworkInterface.GetAllNetworkInterfaces()) {
if(ni.NetworkInterfaceType == NetworkInterfaceType.Wireless80211 ||
ni.NetworkInterfaceType == NetworkInterfaceType.Ethernet) {
Console.WriteLine(ni.Name);
}
}
并获取计算机的所有托管 IPv4 地址:
IPAddress [] IPS = Dns.GetHostAddresses(Dns.GetHostName());
foreach (IPAddress ip in IPS) {
if (ip.AddressFamily == AddressFamily.InterNetwork) {
Console.WriteLine("IP address: " + ip);
}
}
但是如何获取网络接口(interface)及其正确的 ipv4 地址呢?
最佳答案
foreach(NetworkInterface ni in NetworkInterface.GetAllNetworkInterfaces())
{
if(ni.NetworkInterfaceType == NetworkInterfaceType.Wireless80211 || ni.NetworkInterfaceType == NetworkInterfaceType.Ethernet)
{
Console.WriteLine(ni.Name);
foreach (UnicastIPAddressInformation ip in ni.GetIPProperties().UnicastAddresses)
{
if (ip.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
{
Console.WriteLine(ip.Address.ToString());
}
}
}
}
这应该可以满足您的需求。 ip.Address 是您想要的 IP 地址。
关于c# - 如何获取网络接口(interface)及其正确的 IPv4 地址?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9855230/