asp.net获取IP地址mac地址

15 篇文章 0 订阅
11 篇文章 0 订阅

一、本机

获取服务器的IP地址方法以DNS法较为简单实用,如下:

private void ButtonIP_Click(object sender, System.EventArgs e)
{ 
System.Net.IPAddress[] addressList = Dns.GetHostByName(Dns.GetHostName()).AddressList;

if ( addressList.Length>1)

{ TextLIP.Text = addressList[0].ToString();

TextSIP.Text = addressList[1].ToString();

}

else

{

TextLIP.Text = addressList[0].ToString();

TextSIP.Text = "没有可用的连接";

}
}

获取服务器的IP地址与MAC地址另一方法如下:

using System.Management;
string stringMAC = "";
string stringIP = "";
ManagementClass MC = new ManagementClass ("Win32_NetworkAdapterConfiguration");
ManagementObjectCollection MOC= MC.GetInstances();
foreach(ManagementObject MO in MOC)
{
  if ((bool)MO["IPEnabled"] == true)
  {
    stringMAC += MO["MACAddress"].ToString();
    TextMAC.Text = stringMAC.ToString();
    string[] IPAddresses = (string[]) MO["IPAddress"];
    if(IPAddresses.Length > 0)
        stringIP = IPAddresses[0];
        TextIP.Text = stringIP.ToString();
  }
}

获取客户端本机的IP地址相当简易,方法如下:

using System.Net;
TextIP.Text=Page.Request.UserHostAddress;

二、客户端

有两种方法:

1,通过win32特性获得,

        优点:无需在客户端设置;缺点:无法获取服务器的mac(经测试总为0,其实感觉没有必要获取服务器的mac,所以也不算缺点)(能否跨网段获取还没有测试) 

      using System.Runtime.InteropServices; 
     [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 void Page_Load(object sender, System.EventArgs e) 
      { 
           try
           { 
                string userip=Request.UserHostAddress; 
                string strClientIP = Request.UserHostAddress.ToString().Trim(); 
                Int32 ldest = inet_addr(strClientIP); //目的地的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 + "的朋友!" + "<br>"); 
                    } 
                     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+ "<br>" + ",MAC地址为"+mac_dest+"的朋友!" 
  
                 +   "<br>"); 
           } 
           catch(Exception err)  
           {  
                Response.Write(err.Message); 
           } 
      }

2,通过javascript加载ActiveX来实现:

       优点:任意获取mac地址(可以跨网段获取);缺点:需要在客户端浏览器中将activeX的选项全部打开,否则获取不到,所以不怎么稳定;

首先,写入Javascript代码

// JScript 文件 
  
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) 
{ 
    //获取失败 
}

然后调用上面的JS

/// <summary> 
    /// 获取mac地址 
    /// </summary> 
    /// <returns></returns> 
    public string GetMACs() 
    { 
         try
        { 
            return Request.Form["txtMAC"].ToString(); 
        } 
        catch
        { 
  
            return ""; 
        } 
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值