在做B/S結構的系統時,我們常常需要取得客戶端的一些信息,如IP和MAC,以結合身份驗證。在ASP.NET中,要取得伺服器端的MAC很容易,但是要取得客戶端的MAC的位址確要花費一翻心思,通常的做法是呼叫Win32API或直接呼叫nbtstat指令,這樣做有很多問題,而另一種方法就是直接用客戶端腳本,我們在這裡用Javascript,這樣做的好處是不需要伺服器端進行處理,有客戶端自行獲取,傳遞到伺服器端,且速度和可靠性都比在伺服器端取得好。
具體實現的html和javascript如下:
<HTML><HEAD><TITLE>WMI Scripting HTML</TITLE>
<META http-equiv=Content-Type content="text/html; charset=gb2312">
<SCRIPT language=JScript event="OnCompleted(hResult,pErrorObject, pAsyncContext)" for=foo>
document.forms[0].txtMACAddr.value=unescape(MACAddr);
document.forms[0].txtIPAddr.value=unescape(IPAddr);
document.forms[0].txtDNSName.value=unescape(sDNSName);
//document.formbar.submit();
</SCRIPT>
<SCRIPT language=JScript event=OnObjectReady(objObject,objAsyncContext) for=foo>
if(objObject.IPEnabled != null && objObject.IPEnabled != "undefined" && objObject.IPEnabled == true)
{
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;
}
</SCRIPT>
<META content="MSHTML 6.00.2800.1106" name=GENERATOR></HEAD>
<BODY>
<OBJECT id=locator classid=CLSID:76A64158-CB41-11D1-8B02-00600806D9B6 VIEWASTEXT></OBJECT>
<OBJECT id=foo classid=CLSID:75718C9A-F029-11d1-A1AC-00C04FB6C223></OBJECT>
<SCRIPT language=JScript>
var service = locator.ConnectServer();
var MACAddr ;
var IPAddr ;
var DomainAddr;
var sDNSName;
service.Security_.ImpersonationLevel=3;
service.InstancesOfAsync(foo, 'Win32_NetworkAdapterConfiguration');
</SCRIPT>
<FORM id=formfoo name=formbar action=NICPost.asp method=post><INPUT value=00:05:5D:0E:C7:FA name=MACAddr> <INPUT value=192.168.0.2 txt=IPAddr> <INPUT value=192.168.0.2 txt=IPAddr > <INPUT value=typ name=txtDNSName> </FORM></BODY></HTML>
關鍵是用到兩個ActiveX:
<OBJECT id=locator classid=CLSID:76A64158-CB41-11D1-8B02-00600806D9B6 VIEWASTEXT></OBJECT>
<OBJECT id=foo classid=CLSID:75718C9A-F029-11d1-A1AC-00C04FB6C223></OBJECT>
不過這兩個ActiveX都是系統自帶,不用去下載或註冊。
接下來的工作就是用腳本和ActiveX交互,腳本可以是js或Vbs我個人喜歡用js。