zoukankan      html  css  js  c++  java
  • 总结 asp.net 和 javascript获取本地IP(MAC)和服务器IP(MAC)的方法

    1.Asp.net

    1.1获取客户端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;
      }
     

    1.2获取客户端MAC地址:

    //方法一

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

    1.3获取客户端MAC地址

    //方法二

    using System.Text.RegularExpressions;
    using System.Diagnostics;
    public class test
    {
            public test
            {}
            public static string GetCustomerMac(string IP) //para IP is the client's IP
            {
                   string dirResults="";
                   ProcessStartInfo psi  = new ProcessStartInfo();
                   Process proc = new Process();
                   psi.FileName = "nbtstat";
                   psi.RedirectStandardInput = false;
                   psi.RedirectStandardOutput = true;
                   psi.Arguments = "-A " + IP;
                   psi.UseShellExecute = false;
                   proc = Process.Start(psi);
                   dirResults = proc.StandardOutput.ReadToEnd();
                   proc.WaitForExit();
                   dirResults=dirResults.Replace("\r","").Replace("\n","").Replace("\t","");

                  Regex reg=new Regex("Mac[ ]{0,}Address[ ]{0,}=[ ]{0,}(?((.)*?)) __MAC",RegexOptions.IgnoreCase|RegexOptions.Compiled);
                   Match mc=reg.Match(dirResults+"__MAC");

               if(mc.Success)
                {
                    return mc.Groups["key"].Value;
               }
                else
               {
                    reg=new Regex("Host not found",RegexOptions.IgnoreCase|RegexOptions.Compiled);
                    mc=reg.Match(dirResults);
                if(mc.Success)
                {
                     return "Host not found!";
                }
                else
                {
                     return "";
                }
           }
      }
    }

     

    1.4获取服务器的IP地址方法(DNS法)


      using System.Net;
     
     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 = "没有可用的连接";
         }
      }

    1.5获取服务器的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();
        }
     }

    2.Javascript

    2.1获取客户端IP及MAC

    <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=txtMACAddr> <INPUT value=192.168.0.2 name=txtIPAddr> <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都是系统自带,不用去下载或注册。


    2.2获取客户端IP(这个ActiveX需要设置,不建议使用)

    <script type="text/javascript" language="javascript">
    <!--
    function GetLocalIPAddress()
    {
    var obj = null;
    var rslt = "";
    try
    {
    obj = new ActiveXObject("rcbdyctl.Setting");
    rslt = obj.GetIPAddress;
    obj = null;
    }
    catch(e)
    {
    //异常发生
    }

    return rslt;
    }

    在使用中可能会出现类似下图的警告,点击“是”,就可以运行了
    也可以在【Internet 选项】中【安全】->【ActiveX 控件和插件】->【对没有标记为安全的 ActiveX 控件进行初始化和脚本运行】设置为【启用】,
    就不会弹出对话框了。有时候测试时因代码出错既不弹出对话框,也不显示 IP,更正代码后也是一样的情况,这时你需要重新打开 IE 进行测试,在实际使用中,不会出现类似情况。


    2.3javascript获取服务器IP

    直接访问是不行的,但是如果间接访问,将它放在页面的一个隐藏控件里就好了

  • 相关阅读:
    php 可变函数用法
    javascript语法里一些难点问题
    jquery技巧总结
    Bootstrap学习笔记
    Linux下中文文件名乱码问题的详解
    php中iconv函数使用方法,解决中文乱码
    web制作、开发人员需知的Web缓存知识
    鲍鱼开始讲八皇后了
    鲍鱼开始讲八皇后了
    double links....baoyuzuoye
  • 原文地址:https://www.cnblogs.com/vampiredaniel/p/2286190.html
Copyright © 2011-2022 走看看