在DLL中获取客户端的IP和URL
时间:2010-10-26 来源:天一直很蓝
代码
using System;
using System.Collections.Generic;
using System.Net;
using System.Web;
namespace FreeShadow
{
/// <summary>
/// 功能说明:在DLL里面获取IP和URL
/// </summary>
public class IPAndUrlHelper
{
/// <summary>
/// 获取主机IP
/// </summary>
/// <returns></returns>
public static string GetHostIP()
{
string hostIp = string.Empty;
try
{
System.Net.IPAddress[] addressList = Dns.GetHostEntry(Dns.GetHostName()).AddressList;
foreach (IPAddress ip in addressList)
{
if (ip.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
{
hostIp = ip.ToString();
break;
}
}
return hostIp;
}
catch (Exception)
{
return hostIp;
}
}
/// <summary>
/// 获取客户端IP
/// </summary>
/// <returns></returns>
public static string GetClientIP()
{
try
{
string result = string.Empty;
result = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
if (string.IsNullOrEmpty(result))
{
result = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
}
if (string.IsNullOrEmpty(result))
{
result = HttpContext.Current.Request.UserHostAddress;
}
return result;
}
catch
{
return "无法解析IP";
}
}
/// <summary>
/// 获取服务器IP、Mac地址
/// </summary>
/// <returns></returns>
public static List<string> GetHostIPAndMac()
{
try
{
List<string> list = new List<string>();
System.Net.IPAddress[] addressList = Dns.GetHostEntry(Dns.GetHostName()).AddressList;
if (addressList.Length > 1)
{
list.Add(addressList[0].ToString());
list.Add(addressList[1].ToString());
}
else
{
list.Add(addressList[0].ToString());
list.Add("没有可用的连接");
}
return list;
}
catch (Exception)
{
return null;
}
}
/// <summary>
/// 获取库户端请求的Url
/// </summary>
/// <returns></returns>
public static string GetClientUrl()
{
if(HttpContext.Current == null)
{
return "无法获取,该日志不是来源于Web";
}
try
{
string result = HttpContext.Current.Request.Url.ToString();
if (string.IsNullOrEmpty(result))
{
result = HttpContext.Current.Request.ServerVariables["Path_Info"];
}
if (string.IsNullOrEmpty(result))
{
result = HttpContext.Current.Request.UserHostAddress;
}
return result;
}
catch (Exception)
{
return "获取失败";
}
}
}
}
相关阅读 更多 +