一、使用Dns類獲取本機IP
1、Dns類是System.Net命名空間下的一個類,它提供了網路主機名解析服務。使用Dns.GetHostEntry()方法可以獲取本機的IP信息。
using System.Net; IPAddress[] ipaddrs = Dns.GetHostEntry(Dns.GetHostName()).AddressList; foreach (IPAddress ipaddr in ipaddrs) { Console.WriteLine("IP Address: " + ipaddr.ToString()); }
2、上面的代碼會列印出當前機器的所有IP地址
二、使用IPGlobalProperties類獲取本機IP
1、IPGlobalProperties類提供了訪問IP協議的全局信息,如連接數、埠號和網路介面信息等。
using System.Net.NetworkInformation; IPGlobalProperties computerProperties = IPGlobalProperties.GetIPGlobalProperties(); NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces(); foreach (NetworkInterface adapter in nics) { IPInterfaceProperties properties = adapter.GetIPProperties(); foreach (IPAddressInformation address in properties.UnicastAddresses) { Console.WriteLine("IP Address: " + address.Address.ToString()); } }
2、上面的代碼可以獲取到本機所有的IPv4和IPv6地址。
三、使用WMI獲取本機IP
1、WMI是Windows Management Instrumentation的縮寫,是Windows提供的一種管理技術,可以通過C#編寫的WMI查詢語句來獲取系統信息,包括本機的IP地址。
using System.Management; ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration"); ManagementObjectCollection moc = mc.GetInstances(); foreach (ManagementObject mo in moc) { if ((bool)mo["IPEnabled"] == true) { Console.WriteLine("IP Address: " + ((string[])mo["IPAddress"])[0]); } }
2、上面的代碼通過WMI查詢Win32_NetworkAdapterConfiguration類來獲取所有啟用了IP的網路適配器的IP地址。
四、使用網路介面類獲取本機IP
1、網路介面類(NetworkInterface)定義了網路適配器的屬性和行為,可以通過這個類獲取本機的IP地址。
using System.Net.NetworkInformation; NetworkInterface[] adapters = NetworkInterface.GetAllNetworkInterfaces(); foreach (NetworkInterface adapter in adapters) { IPInterfaceProperties adapterProperties = adapter.GetIPProperties(); foreach (UnicastIPAddressInformation address in adapterProperties.UnicastAddresses) { Console.WriteLine("IP Address: " + address.Address.ToString()); } }
2、上面的代碼通過NetworkInterface.GetAllNetworkInterfaces()方法獲取所有的網路介面,然後通過逐個網路介面的IPInterfaceProperties屬性來獲取IP地址。
五、使用Socket類獲取本機IP
1、Socket類提供了網路編程介面,可以通過它獲取本機的IP地址。
using System.Net; using System.Net.Sockets; IPHostEntry hostEntry = Dns.GetHostEntry(Dns.GetHostName()); foreach (IPAddress ipAddr in hostEntry.AddressList) { if (ipAddr.AddressFamily == AddressFamily.InterNetwork) { Console.WriteLine("IP Address: " + ipAddr.ToString()); } }
2、上面的代碼通過獲取本機名來獲取本機的IP信息。
六、總結
本文介紹了5種方式獲取C#中本機的IP地址,通過這些方法,我們可以很輕鬆地獲取到本機的IP地址信息,以便在網路編程中使用。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/254057.html