Challenge: Identify the IP address assigned to your computer by your router, excluding addresses from network interfaces (like a direct modem connection).
Solution:
This C# code snippet efficiently retrieves your computer's local IP address:
<code class="language-csharp">public static string GetLocalIPAddress() { var hostInfo = Dns.GetHostEntry(Dns.GetHostName()); foreach (var ipAddress in hostInfo.AddressList) { if (ipAddress.AddressFamily == AddressFamily.InterNetwork) { return ipAddress.ToString(); } } throw new Exception("No IPv4 address found on the system!"); }</code>
The code iterates through the IP addresses associated with your computer and returns the first IPv4 address it encounters. If no IPv4 address is detected, an exception is raised.
Verifying Network Connection:
To confirm network connectivity, use this simple C# method:
<code class="language-csharp">System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable();</code>
This returns true
if a network connection is active, and false
otherwise.
The above is the detailed content of How Can I Get My Computer's Local IP Address in C#?. For more information, please follow other related articles on the PHP Chinese website!