雷达智富

首页 > 内容 > 程序笔记 > 正文

程序笔记

C#中获取本机IP地址、HostName 和DNS名称

2024-08-20 64

C#中获取本机IP地址、HostName 和DNS名称,参考代码片段如下:

string LocalIp = string.Empty;
string Domain = System.Net.NetworkInformation.IPGlobalProperties.GetIPGlobalProperties().DomainName;
string Host = System.Net.Dns.GetHostName();

if (!System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable())
{
    return null;
}

System.Net.IPHostEntry host = System.Net.Dns.GetHostEntry(System.Net.Dns.GetHostName());
foreach (System.Net.IPAddress ip in host.AddressList)
{
    if (ip.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
    {
       LocalIp = ip.ToString();
       break;
    }
}

Console.WriteLine([Domain:{0}, Host:{1},  IP:{2}], Domain, Host, LocalIp);  

获取到IP地址、HostName 和DNS名称信息输出参考内容如下:

[Domain: ferris.intranet, Host:ferris-pc, IP: 192.168.1.2]

更新于:3个月前
赞一波!2

文章评论

评论问答