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
Release: 2025-01-24 19:42:39
Original
449 people have browsed it

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>
Copy after login

Confirming Network Availability

The following simple method checks for an active network connection:

<code class="language-csharp">System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable();</code>
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template