Home > Backend Development > C++ > How Can I Efficiently Retrieve My Local IP Address and Verify Network Connectivity?

How Can I Efficiently Retrieve My Local IP Address and Verify Network Connectivity?

Susan Sarandon
Release: 2025-01-24 19:46:11
Original
393 people have browsed it

How Can I Efficiently Retrieve My Local IP Address and Verify Network Connectivity?

Efficiently obtain local IP address and network connection status

There are many ways to obtain a local IP address. One common method is to use the Dns.GetHostName() and Dns.GetHostEntry() methods to obtain a list of hostnames and IP addresses:

<code class="language-csharp">string strHostName = string.Empty;

// 获取本地计算机的主机名
strHostName = Dns.GetHostName();
Console.WriteLine("本地计算机主机名: " + strHostName);

// 使用主机名获取IP地址列表
IPHostEntry ipEntry = Dns.GetHostEntry(strHostName);
IPAddress[] addr = ipEntry.AddressList;

for (int i = 0; i < addr.Length; i++)
{
    Console.WriteLine("IP Address {0}: {1}", i, addr[i].ToString());
}</code>
Copy after login

However, if you only want to get the LAN IP address assigned by the router, this method may not provide ideal results. Additionally, you must determine whether your computer is connected to the network.

Get local IP address

To do this, consider using the following methods:

<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("系统中没有具有IPv4地址的网络适配器!");
}</code>
Copy after login

This method iterates through a list of IP addresses to retrieve the first IPv4 address, which is usually a LAN IP address.

Check network connection

To determine if your computer is connected to the network, use the following expression:

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

If there is a network connection, this expression returns true; otherwise it returns false.

The above is the detailed content of How Can I Efficiently Retrieve My Local IP Address and Verify Network Connectivity?. 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