Home > Backend Development > C++ > How Can I Get My Computer's Local IP Address in C#?

How Can I Get My Computer's Local IP Address in C#?

Patricia Arquette
Release: 2025-01-24 19:51:16
Original
924 people have browsed it

How Can I Get My Computer's Local IP Address in C#?

Retrieving Your Local IP Address in C#

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

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

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!

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