获取电脑IP和MAC

using System.Web;

using System.Diagnostics;

using System.Text.RegularExpressions;

需要System.Web.dll

 1 /// <summary>
 2 /// 取得用户客户端IP(穿过代理服务器取远程用户真实IP地址)
 3 /// </summary>
 4 public static string GetClientIP()
 5 {
 6 
 7      //如果使用代理,获取真实IP   
 8      string userip = string.Empty;
 9      if (HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] != "")
10      {
11           userip = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
12      }
13      else
14      {
15           userip = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
16      }
17      if (userip == null || userip == "")
18      {
19           userip = HttpContext.Current.Request.UserHostAddress;
20      }
21      return userip; 
22 
23      //HttpRequest Request = HttpContext.Current.Request;
24      //try
25      //{
26      //    if (HttpContext.Current.Request.ServerVariables["HTTP_VIA"] != null)
27      //    {
28      //        return HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"].ToString();
29      //    }
30      //    else
31      //    {
32      //        return HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"].ToString();
33      //    }
34      //}
35      //catch { return "127.0.0.1"; }
36      }
37      //获取mac地址
38     public static string GetCustomerMac()
39      {
40           string IP = GetClientIP();
41           string dirResults = "";
42           ProcessStartInfo psi = new ProcessStartInfo();
43           Process proc = new Process();
44           psi.FileName = "nbtstat";
45           psi.RedirectStandardInput = false;
46           psi.RedirectStandardOutput = true;
47           psi.Arguments = "-a " + IP;
48           psi.UseShellExecute = false;
49           proc = Process.Start(psi);
50           dirResults = proc.StandardOutput.ReadToEnd();
51           proc.WaitForExit();
52 
53           //匹配mac地址
54        Match m = Regex.Match(dirResults, "\\w+\\-\\w+\\-\\w+\\-\\w+\\-\\w+\\-\\w\\w");
55 
56           //若匹配成功则返回mac,否则返回找不到主机信息
57        if (m.ToString() != "")
58           {
59                return m.ToString();
60           }
61           else
62           {
63                return "找不到主机信息";
64           }
65      }

 

 

posted @ 2012-12-26 18:14  EleMMent  阅读(386)  评论(0编辑  收藏  举报