• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

asp.net获得客户端mac地址

原作者: [db:作者] 来自: [db:来源] 收藏 邀请
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Runtime.InteropServices;

namespace WebTestMac
{
    public partial class WebForm1 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            string str = GetCustomerMac(GetClientIP());
            Response.Write(str);
        }
        [DllImport("Iphlpapi.dll")]
        private static extern int SendARP(Int32 dest, Int32 host, ref Int64 mac, ref Int32 length);
        [DllImport("Ws2_32.dll")]
        private static extern Int32 inet_addr(string ip);

        private string GetClientIP()
        {
            string result = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
            if (null == result || result == String.Empty)
            {
                result = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
            }

            if (null == result || result == String.Empty)
            {
                result = HttpContext.Current.Request.UserHostAddress;
            }
            return result;
        }
        /// <summary>   
        /// 获取Mac地址信息   
        /// </summary>   
        /// <param name="IP"></param>   
        /// <returns></returns>   
        public static string GetCustomerMac(string IP)
        {
            Int32 ldest = inet_addr(IP);
            Int64 macinfo = new Int64();
            Int32 len = 6;
            int res = SendARP(ldest, 0, ref macinfo, ref len);
            string mac_src = macinfo.ToString("X");

            while (mac_src.Length < 12)
            {
                mac_src = mac_src.Insert(0, "0");
            }

            string mac_dest = "";

            for (int i = 0; i < 11; i++)
            {
                if (0 == (i % 2))
                {
                    if (i == 10)
                    {
                        mac_dest = mac_dest.Insert(0, mac_src.Substring(i, 2));
                    }
                    else
                    {
                        mac_dest = "-" + mac_dest.Insert(0, mac_src.Substring(i, 2));
                    }
                }
            }

            return mac_dest;
        }

    }
}


今天才发现 MAC 地址是 16 进制的。

macinfo.ToString("X") 获得 居然 是 倒过来的 mac 地址

测试有点失败,只能是局域网的mac,不是广域网的mac

ToString("X")  就是显示为16 进制。参见:

http://msdn.microsoft.com/zh-cn/library/1fd69cbc(v=vs.110).aspx

        string GetMacAddress()
        {
            try
            {
                string mac = "";
                ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration");
                ManagementObjectCollection moc = mc.GetInstances();
                foreach (ManagementObject mo in moc)
                {
                    if ((bool)mo["IPEnabled"] == true)
                    {
                        mac = mo["MacAddress"].ToString();
                        break;
                    }
                }
                moc = null;
                mc = null;
                return mac;
            }
            catch
            {
                return "unknow";
            }
        }

 

这种方法是获取服务器的MAC

 

方式三:通过javascript加载ActiveX来实现:

       优点:任意获取mac地址(可以跨网段获取);

       缺点:需要在客户端浏览器中将activeX的选项全部打开,否则获取不到,所以不怎么稳定;

前台代码:(WebForm3.aspx)

 

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm3.aspx.cs" Inherits="WebApp.WebForm3" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title></title>
            <mce:script language="javascript"><!--
        document.write("<OBJECT id='locator' classid='CLSID:76A64158-CB41-11D1-8B02-00600806D9B6' VIEWASTEXT></OBJECT>");
        document.write("<OBJECT id=foo classid=CLSID:75718C9A-F029-11d1-A1AC-00C04FB6C223></OBJECT>");
        var MACAddr, IPAddr, sDNSName
        function getObject(objObject, objAsyncContext) {
            try {
                if (MACAddr == null && objObject.IPEnabled) {
                    if (objObject.MACAddress != null && objObject.MACAddress != "undefined")
                        MACAddr = objObject.MACAddress;
                    if (objObject.IPEnabled && objObject.IPAddress(0) != null && objObject.IPAddress(0) != "undefined")
                        IPAddr = objObject.IPAddress(0);
                    if (objObject.DNSHostName != null && objObject.DNSHostName != "undefined")
                        sDNSName = objObject.DNSHostName;
                }
            }
            catch (err)
            { }
        }
        function setValue(hResult, pErrorObject, pAsyncContext) {
            createTxt("txtMAC", MACAddr);
            createTxt("txtIp", IPAddr);
            createTxt("txtPCName", sDNSName);
        }
        function createTxt(txtName, txtValue) {
            var macTxt = document.createElement("INPUT");
            macTxt.name = txtName;
            macTxt.value = txtValue;
            macTxt.type = "hidden";
            try {
                document.forms[0].appendChild(macTxt);
            }
            catch (err) {
                //获取失败
            }
        }
        document.getElementById("foo").attachEvent("OnObjectReady", getObject);
        document.getElementById("foo").attachEvent("OnCompleted", setValue);
        try {
            var service = locator.ConnectServer();
            var MACAddr;
            var IPAddr;
            var DomainAddr;
            var sDNSName;
            service.Security_.ImpersonationLevel = 3;
            service.InstancesOfAsync(foo, 'Win32_NetworkAdapterConfiguration');
        }
        catch (err) {
            //获取失败
        }
    
// --></mce:script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    
        <asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Button" />
    
    </div>
    </form>
</body>
</html>

 

 

后台代码:(WebForm3.aspx.cs)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace WebApp
{
    public partial class WebForm3 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
        }
        /// <summary>
        /// 获取mac地址
        /// </summary>
        /// <returns></returns>
        public string GetMACs()
        {
            try
            {
                return Request.Form["txtMAC"].ToString();
            }
            catch
            {
                return "";
            }
        }
        protected void Button1_Click(object sender, EventArgs e)
        {
            Response.Write(GetMACs());
        }
    }
}

 

 

运行提示:

启用未标记为可安全执行脚本的ActiveX 第一步:工具->Internet选项 第二步:安全->Internet->自定义级别 第三步:启用“对未标记为可安全执行脚本的ActiveX控件初始化并执行”,如下图所示:

运行结果:

 

 

 第三种未测试,这种太不人性化了,而且不安全

 

现在打算 搞 c# 插件开发

百度 搜索  网页插件开发 c#

找到了几个案例 ,唉,我试验失败

http://blog.csdn.net/zhang_88888888/article/details/6721620

 

 


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap