写面向过程一年多了,突然转向面向对象,感觉特别的不适应,一个简单的程序,足足写了几天。还没写得很完整。最开始一直以为是用IPHostEntry类来获取IPv4地址,直到在论坛,博客上找了好久才发现是在 System.Net.NetworkInformationUni.castIPAddressInformation里面获取IPv4跟子网掩码的。还是太菜了。写个这么简单的程序都得这么多天。以后要更加勤的练习了。
using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows;using System.Windows.Controls;using System.Windows.Data;using System.Windows.Documents;using System.Windows.Input;using System.Windows.Media;using System.Windows.Media.Imaging;using System.Windows.Navigation;using System.Windows.Shapes;using System.Net;using System.Net.Sockets;using System.Net.NetworkInformation; //调用命名空间namespace Ipconfig{ /// <summary> /// MainWindow.xaml 的交互逻辑 /// </summary> public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); } PRivate void Window_Loaded(object sender, RoutedEventArgs e) { //获取本机名称 string Host_name = Dns.GetHostName(); listBox.Items.Add("本机名称: " + Host_name); listBox.Items.Add("-----------------------------------------------------------------------------"); NetworkInterface[] NwIfs = NetworkInterface.GetAllNetworkInterfaces(); listBox.Items.Add("配适器的数量为: " + (NwIfs.Length - 1)); int Index = 1; foreach (NetworkInterface NwIf in NwIfs) { if (NetworkInterfaceType.Loopback == NwIf.NetworkInterfaceType) continue; //获取配适器基本信息 listBox.Items.Add("------------------------------- 第" + (Index++) + "个配适器 --------------------------------"); listBox.Items.Add("名称: " + NwIf.Name); listBox.Items.Add("描述: " + NwIf.Description); byte[] Phy = NwIf.GetPhysicalAddress().GetAddressBytes(); listBox.Items.Add("物理地址: " + BitConverter.ToString(Phy)); IPInterfaceProperties Propers = NwIf.GetIPProperties(); //获取配适器IP地址 foreach (UnicastIPAddressInformation UipI in Propers.UnicastAddresses) { if (UipI.Address.AddressFamily == AddressFamily.InterNetwork) { listBox.Items.Add("IPv4: " + UipI.Address); listBox.Items.Add("子网掩码: " + UipI.IPv4Mask); } if(UipI.Address.AddressFamily == AddressFamily.InterNetworkV6) { listBox.Items.Add("IPv6: " + UipI.Address); } } //获取配适器网关地址 if (Propers.GatewayAddresses.Count > 0) { listBox.Items.Add("网关: " + Propers.GatewayAddresses[0].Address); } //获取配适器DNS地址 if (Propers.DnsAddresses.Count > 0) { listBox.Items.Add("DNS: " + Propers.DnsAddresses[0]); } } } }}新闻热点
疑难解答