获取本地Mac地址
public string GetMAC()
{
using (System.Management.ManagementClass mc = new System.Management.ManagementClass("Win32_NetworkAdapterConfiguration"))
{
System.Management.ManagementObjectCollection moc = mc.GetInstances();
foreach (System.Management.ManagementObject mo in moc)
{
if ((bool)mo["IPEnabled"])
return mo["MacAddress"].ToString().Replace("-", ":").ToUpper();
}
}
return null;
}
添加System.Management.dll
获取服务器IP
#region 得到用户IP地址
/// <summary>
///
/// </summary>
/// <returns></returns>
public static string GetIPAddress()
{
//HTTP_VIA代理服务器 IP
//HTTP_X_FORWARDED_FOR = 用户的真实 IP ,经过多个代理服务器时,这个值类似如下:203.98.182.163, 203.98.182.163, 203.129.72.215。
string user_IP = string.Empty;
if (System.Web.HttpContext.Current.Request.ServerVariables["HTTP_VIA"] != null)
{
if (System.Web.HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] != null)
{
user_IP = System.Web.HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"].ToString();
}
else
{
user_IP = System.Web.HttpContext.Current.Request.UserHostAddress;
}
}
else
{
user_IP = System.Web.HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"].ToString();
}
return user_IP;
}
#endregion
//获取客户端动态IP地址
public string GetCustomerIP()
{
string CustomerIP="";
if(HttpContext.Current.Request.ServerVariables["HTTP_VIA"]!=null)
{
CustomerIP=HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"].ToString();
}
else
{
CustomerIP=HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"].ToString();
}
return CustomerIP;
}
验证Mac 及 Ip
/// <summary>
/// 验证IP地址格式
/// </summary>
/// <param name="TestIp"></param>
/// <returns></returns>
public bool VaildIpv4(string TestIp)
{
string num = "(25[0-5]|2[0-4]//d|[0-1]//d{2}|[1-9]?//d)";
return Regex.IsMatch(TestIp, ("^" + num + "//." + num + "//." + num + "//." + num + "$"));
}
/// <summary>
/// 验证Mac 地址格式
/// </summary>
/// <param name="testMac"></param>
/// <returns></returns>
public bool VaildMac(string testMac)
{
string Reg = @"^([0-9a-fA-F]{2})(([//s:-][0-9a-fA-F]{2}){5})$";
if (Regex.IsMatch(testMac, Reg))
return true;
else
return false;
}