zoukankan      html  css  js  c++  java
  • Asp.net 根据IP地址获取跨网段mac地址函数【搜藏】

    根据ip地址获取mac地址的方法网上有很多,但是由于路由器的关系,只能局限于获取同网段的ip的mac地址,后来知道了一个dos命令"nbtstat",这个命令就可以跨网段获取mac,不过测试过有一些地址还是获取不了,好像开了防火墙就不行,后来找到一段代码,原理就是根据这个命令获取返回的数据然后用正则表达式进行mac信息段的截取,如下:

        //通过IP地址获取MAC地址的方法(可跨网段获取)        
       string GetMac(string 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,}(?<key>((.)*?))__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 ""; }
            }
        }
    

    asp.net中调用如下:

    //获取客户端ip地址
    string ipAddress = Request.UserHostAddress.ToString().Trim();
    //调用函数得到mac地址
    string macAddress = GetMac(ipAddress);
    
  • 相关阅读:
    架构设计
    Asp.net MVC突然变慢,缓存消失的一种原因
    B2C电子商务系统研发——商品SKU分析和设计(二)
    ASP.NET MVC下基于异常处理的完整解决方案
    【C#.NET】利用FastDFS打造分布式文件系统
    C#
    50个必备的实用jQuery代码段
    可视化组件库(The Visual Component Library)
    TortoiseHg 2.2.2
    企业信息开发平台
  • 原文地址:https://www.cnblogs.com/linyc/p/2002849.html
Copyright © 2011-2022 走看看