c#获取本地连接的ip 子网掩码 网关 DNS

一时兴起 想写一个获取电脑本地连接的ip 等信息的c#程序

网上流传的获取正在上网的ip较多 大致如下:

     //获取上网的ip  需要联网才可以 不联网输出127.0.0.1 并不是我想要的
            string name = Dns.GetHostName();
            IPAddress[] ipadrlist = Dns.GetHostAddresses(name);
            foreach (IPAddress ipa in ipadrlist)
            {
                if (ipa.AddressFamily == AddressFamily.InterNetwork)
                    MessageBox.Show(ipa.ToString());
            }

想找一个获取本地连接的ip的程序 网上的大多太简单了 好多程序并不完善 针对性比较强 通用的较少

所以自己用c#编了一个自认为还比较健壮的小程序 代码如下

     //获取本地连接ip 掩码 网关 DNS
            NetworkInterface[] interfaces = NetworkInterface.GetAllNetworkInterfaces();
            foreach (NetworkInterface bendi in interfaces)
            {
                if (bendi.Name.ToString().Equals("本地连接") && bendi.NetworkInterfaceType.ToString().Equals("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());
                }
            }
代码可能还有不完善的地方 仅供参考








  • 1
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

大米粥哥哥

感谢认可!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值