C#如何获取Ip地址
此处我在某一个项目上,客户这边让我们在系统日志中添加登陆者和被访问者Ip,所以再次研究出这套程序,亲测可用。
/// <summary>
/// 获取Ip
/// </summary>
public static string Ip
{
·get
{
var result = string.Empty;
if (HttpContext.Current != null)
result = GetWebClientIp();
if (result.IsEmpty())
result = GetLanIp();
return result;
}
}
/// <summary>
/// 获取Web客户端的Ip
/// </summary>
public static string GetWebClientIp()
{
var ip = GetWebRemoteIp();
foreach (var hostAddress in Dns.GetHostAddresses(ip))
{
if (hostAddress.AddressFamily == AddressFamily.InterNetwork)
return hostAddress.ToString();
}
return string.Empty;
}
/// <summary>
/// 获取Web远程Ip
/// </summary>
private static string GetWebRemoteIp()
{
return HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] ?? HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
}
/// <summary>
/// 获取局域网IP
/// </summary>
private static string GetLanIp()
{
foreach (var hostAddress in Dns.GetHostAddresses(Dns.GetHostName()))
{
if (hostAddress.AddressFamily == AddressFamily.InterNetwork)
return hostAddress.ToString();
}
return string.Empty;
}
/// <summary>
/// 获取主机名
/// </summary>
public static string Host
{
get
{
return HttpContext.Current == null ? Dns.GetHostName() : GetWebClientHostName();
}
}
/// <summary>
/// 获取Web客户端主机名
/// </summary>
private static string GetWebClientHostName()
{
if (!HttpContext.Current.Request.IsLocal)
return string.Empty;
var ip = GetWebRemoteIp();
var result = Dns.GetHostEntry(IPAddress.Parse(ip)).HostName;
if (result == "localhost.localdomain")
result = Dns.GetHostName();
return result;
}