ASP.NET獲取客戶端IP及MAC地址

taogchan發表於2013-07-18

朋友最近問如何獲取客戶端IP及MAC地址,一直想把這段給整理一下,契機來了;下邊分為了C#後臺獲取的方法和前臺Javascript(呼叫ActiveX)獲取的方法,大家如果有好的方法一起討論撒O(∩_∩)O


C#程式碼獲取:

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 MyTest
{
    public partial class mac : System.Web.UI.Page
    {
        [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);


        protected void Page_Load(object sender, EventArgs e)
        {
            GetMac(); 
        }

        //獲取客戶端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;
        }

 

        //獲取MAC地址
        private void GetMac()
        {
            // 在此處放置使用者程式碼以初始化頁面
            try
            {
                string userip = Request.UserHostAddress;
                string strClientIP = Request.UserHostAddress.ToString().Trim();
                Int32 ldest = inet_addr(strClientIP); //目的地的ip
                Int32 lhost = 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");
                if (mac_src == "0")
                {
                    if (userip == "127.0.0.1")
                        Response.Write("正在訪問Localhost!");
                    else
                        Response.Write("歡迎來自IP為" + userip + "的朋友!" + "
");
                    return;
                }

                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));
                        }
                    }
                }

                Response.Write("歡迎來自IP為" + userip + "
" + ",MAC地址為" + mac_dest + "的朋友!"

                 + "
");
            }
            catch (Exception err)
            {
                Response.Write(err.Message);
            }


        }
    }
}

Javascript獲取:

<HTML><HEAD><TITLE>WMI Scripting HTMLTITLE>
<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=txtMACAddr> <INPUT value=192.168.0.2 name=txtIPAddr> <INPUT value=typ name=txtDNSName> FORM>BODY>HTML>

來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/22392018/viewspace-766604/,如需轉載,請註明出處,否則將追究法律責任。

相關文章