获取本地连接ip 掩码 网关 DNS

复制代码
//获取本地连接ip 掩码 网关 DNS
            NetworkInterface[] interfaces = NetworkInterface.GetAllNetworkInterfaces();
            foreach (NetworkInterface bendi in interfaces)
            {
                if (bendi.OperationalStatus != OperationalStatus.Up)
                {
                    //break;
                }
                if ((bendi.Name.StartsWith("以太网") || bendi.Name.StartsWith("本地连接")) && bendi.NetworkInterfaceType == NetworkInterfaceType.Ethernet)
                {
                    IPInterfaceProperties ip = bendi.GetIPProperties();
                    //获取Ip 掩码
                    for (int i = 0; i < ip.UnicastAddresses.Count; i++)
                    {
                        //不插网线会得到一个保留地址 169.254.126.164
                        if (ip.UnicastAddresses[i].Address.AddressFamily == AddressFamily.InterNetwork)
                        {
                            if (ip.UnicastAddresses[i].Address != null)
                                MessageBox.Show(ip.UnicastAddresses[i].Address.ToString());
                            //如果不插网线 获取不了掩码 返回null 
                            if (ip.UnicastAddresses[i].IPv4Mask != null)
                                MessageBox.Show(ip.UnicastAddresses[i].IPv4Mask.ToString());
                        }
                    }
                    //获取网关
                    if (ip.GatewayAddresses.Count > 0)
                        MessageBox.Show(ip.GatewayAddresses[0].Address.ToString());
                    //获取DNS     
                    //不要DnsAddresses[0].Address.ToString() 不正确 还有警告  “System.Net.IPAddress.Address”已过时:  
                    if (ip.DnsAddresses.Count > 0)
                        MessageBox.Show(ip.DnsAddresses[0].ToString());
                    //备用DNS
                    if (ip.DnsAddresses.Count > 1)
                        MessageBox.Show(ip.DnsAddresses[1].ToString());
                }
            }
复制代码

 

posted @   邪不压正!  阅读(466)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 25岁的心里话
· 按钮权限的设计及实现
点击右上角即可分享
微信分享提示