Как получить сетевой интерфейс и его правильный IPv4-адрес?
мне нужно знать, как получить все сетевые интерфейсы с их IPv4 адрес. или просто беспроводной и Ethernet.
чтобы получить все детали сетевых интерфейсов я использую это:
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);
}
}
но как получить сетевой интерфейс и его правильный ipv4 адрес?
2 ответов:
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-адрес, который вы хотите.
С некоторым улучшением, этот код добавляет любой интерфейс к комбинации:
private void LanSetting_Load(object sender, EventArgs e) { foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces()) { if ((nic.NetworkInterfaceType == NetworkInterfaceType.Ethernet) || (nic.NetworkInterfaceType == NetworkInterfaceType.Wireless80211)) //&& (nic.OperationalStatus == OperationalStatus.Up)) { comboBoxLanInternet.Items.Add(nic.Description); } } }и при выборе одного из них, этот код возвращает IP-адрес интерфейса:
private void comboBoxLanInternet_SelectedIndexChanged(object sender, EventArgs e) { foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces()) { foreach (UnicastIPAddressInformation ip in nic.GetIPProperties().UnicastAddresses) { if (nic.Description == comboBoxLanInternet.SelectedItem.ToString()) { if (ip.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork) { MessageBox.Show(ip.Address.ToString()); } } } } }
Comments