小编典典

获取本地IP地址

c#

在互联网上,有几个地方向您展示如何获取IP地址。其中很多看起来像这个例子:

String strHostName = string.Empty;
// Getting Ip address of local machine...
// First get the host name of local machine.
strHostName = Dns.GetHostName();
Console.WriteLine("Local Machine's Host Name: " + strHostName);
// Then using host name, get the IP address list..
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());
}
Console.ReadLine();

在此示例中,我获得了几个IP地址,但我只想获得路由器分配给运行该程序的计算机的IP地址:如果某人希望访问我计算机中的共享文件夹以获取该IP,实例。

如果我没有连接到网络,而是直接通过没有路由器的调制解调器连接到了互联网,那么我想得到一个错误。我如何查看我的计算机是否已使用C#连接到网络以及是否要获取LAN
IP地址。


阅读 575

收藏
2020-05-19

共1个答案

小编典典

要获取本地IP地址:

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 network adapters with an IPv4 address in the system!");
}

要检查您是否已连接:

System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable();

2020-05-19