C# 获取ipv4 ip 地址和电脑MAC 地址源代码

C# 获取ipv4 ip 地址和电脑MAC 地址源代码
很多时候我们需要获取电脑的ip地址对程序就行权限的判断,还有电脑mac地址对电脑的锁定,这个时候 ,我们就要获取电脑ipv4 和mac 地址。
下面就是获取IP地址和 Mac 地址的源代码

    /// <summary>
    /// 获取ip 地址
    /// </summary>
    /// <returns></returns>
    public static string GetMyIP()
    {
        IPHostEntry IpEntry = Dns.GetHostEntry(Dns.GetHostName());
        string ip = string.Empty;
        Regex reg = new Regex(@"\d+\.\d+\.\d+\.\d+");

        foreach (var strip in IpEntry.AddressList)
        {
            if (reg.IsMatch(strip.ToString()))
            {
                ip = strip.ToString();
            }
        }
        return ip;
    }

   /// <summary> 
    /// 获取MAC地址(返回第一个物理以太网卡的mac地址) 
    /// </summary> 
    /// <returns>成功返回mac地址,失败返回null</returns> 
    public static string getMacAddress()
    {
        string macAddress = null;
        try
        {
            NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces();
            foreach (NetworkInterface adapter in nics)
            {
                if (adapter.NetworkInterfaceType.ToString().Equals("Ethernet")) //是以太网卡
                {
                    string fRegistryKey = "SYSTEM\\CurrentControlSet\\Control\\Network\\{4D36E972-E325-11CE-BFC1-08002BE10318}\\" + adapter.Id + "\\Connection";
                    RegistryKey rk = Registry.LocalMachine.OpenSubKey(fRegistryKey, false);
                    if (rk != null)
                    {
                        // 区分 PnpInstanceID     
                        // 如果前面有 PCI 就是本机的真实网卡    
                        // MediaSubType 为 01 则是常见网卡,02为无线网卡。    
                        string fPnpInstanceID = rk.GetValue("PnpInstanceID", "").ToString();
                        int fMediaSubType = Convert.ToInt32(rk.GetValue("MediaSubType", 0));
                        if (fPnpInstanceID.Length > 3 && fPnpInstanceID.Substring(0, 3) == "PCI") //是物理网卡
                        {
                            macAddress = adapter.GetPhysicalAddress().ToString();
                            break;
                        }
                        else if (fMediaSubType == 1) //虚拟网卡
                            continue;
                        else if (fMediaSubType == 2) //无线网卡(上面判断Ethernet时已经排除了)
                            continue;
                    }
                }
            }
        }
        catch
        {
            macAddress = null;
        }
        return macAddress;
    }

原文链接:http://www.51jrft.com/jlmb/Others/23991.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值