There are many ways to obtain a local IP address. One common method is to use the Dns.GetHostName()
and Dns.GetHostEntry()
methods to obtain a list of hostnames and IP addresses:
<code class="language-csharp">string strHostName = string.Empty; // 获取本地计算机的主机名 strHostName = Dns.GetHostName(); Console.WriteLine("本地计算机主机名: " + strHostName); // 使用主机名获取IP地址列表 IPHostEntry ipEntry = Dns.GetHostEntry(strHostName); IPAddress[] addr = ipEntry.AddressList; for (int i = 0; i < addr.Length; i++) { Console.WriteLine("IP Address {0}: {1}", i, addr[i].ToString()); }</code>
However, if you only want to get the LAN IP address assigned by the router, this method may not provide ideal results. Additionally, you must determine whether your computer is connected to the network.
Get local IP address
To do this, consider using the following methods:
<code class="language-csharp">public static string GetLocalIPAddress() { var host = Dns.GetHostEntry(Dns.GetHostName()); foreach (var ip in host.AddressList) { if (ip.AddressFamily == AddressFamily.InterNetwork) { return ip.ToString(); } } throw new Exception("系统中没有具有IPv4地址的网络适配器!"); }</code>
This method iterates through a list of IP addresses to retrieve the first IPv4 address, which is usually a LAN IP address.
Check network connection
To determine if your computer is connected to the network, use the following expression:
<code class="language-csharp">System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable();</code>
If there is a network connection, this expression returns true; otherwise it returns false.
The above is the detailed content of How Can I Efficiently Retrieve My Local IP Address and Verify Network Connectivity?. For more information, please follow other related articles on the PHP Chinese website!