日期:2014-05-17  浏览次数:20963 次

c#使用windows的命令nbtstat获得MAC地址

??????? public static string GetRemoteMacByNetBIOS(string clientIP)

??????? {

??????????? string ip = clientIP;

??????????? if ( ip == "127.0.0.1")

??????????????? ip = GetLocalIP()[0];

??????????? string dirResults="";

??????????? ProcessStartInfo psi? = new ProcessStartInfo();

??????????? Process proc = new Process();

??????????? psi.FileName = "nbtstat.exe";

??????????? //psi.RedirectStandardInput = false;

??????????? psi.RedirectStandardOutput = true;psi.RedirectStandardError=true;

??????????? psi.Arguments = "-A " + ip;

??????????? psi.UseShellExecute = false;

??????????? proc = Process.Start(psi);

??????????? dirResults = proc.StandardOutput.ReadToEnd();

??????????? string error = proc.StandardError.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.ToUpper();

??????????? }

??????????? else

??????????? {??????????????????

?????????????? return "";

??????????? }

??????? }

使用此方法需要足够的操作系统的权限。在Web中,可以将ASP.net用户加入 管理员组。

对于上面两个地方都用到的GetLocalIP是一个获取本机IP的方法:

??????? public static string[] GetLocalIP()

??????? {

??????????? string hostName = Dns.GetHostName();

??????????? IPHostEntry ipEntry=Dns.GetHostByName(hostName);

??????????? IPAddress[] arr=ipEntry.AddressList;

??????????? string[] result = new string[arr.Length];

??????????? for(int i=0;i

??????????? {

??????????????? result[i] = arr[i].ToString();?

??????????? }

??????????? return result;

??????? }