Accessing a Network Device's Local IP Address using C#
This article tackles a frequent programming problem: retrieving the local IP address of a machine running a C# application. We'll demonstrate how to:
Retrieving the LAN IP Address
Standard methods for getting a local machine's IP address might return multiple addresses, making it difficult to identify the LAN IP. The solution below addresses this issue.
C# Code for Obtaining the LAN IP Address
This refined code snippet reliably retrieves the LAN IP address:
<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("No IPv4 network adapters found!"); }</code>
Confirming Network Availability
The following simple method checks for an active network connection:
<code class="language-csharp">System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable();</code>
This returns a boolean value indicating the presence of a network connection.
The above is the detailed content of How Can I Get the Local LAN IP Address of a Network-Connected Device in C#?. For more information, please follow other related articles on the PHP Chinese website!