Home >Backend Development >C++ >How Can I Get the Local LAN IP Address of a Network-Connected Device in C#?

How Can I Get the Local LAN IP Address of a Network-Connected Device in C#?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2025-01-24 19:42:39450browse

How Can I Get the Local LAN IP Address of a Network-Connected Device in C#?

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:

  1. Obtain the LAN IP address of a network-connected device.
  2. Verify network connectivity.

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn