using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Net.Http.Headers;
using NPOI.HPSF;
using NPOI.SS.Formula.Functions;
using System.Net;
using System.Net.NetworkInformation;
using System.Net.Sockets;
using System.Web;
namespace WMS.Util
{
///
/// 描 述:网络操作
///
public class NetUtil
{
#region Ip(获取Ip)
///
/// 获取Ip
///
public static string Ip
{
get
{
var result = string.Empty;
if (WebUtil.HttpContext != null)
result = GetWebClientIp();
if (result.IsEmpty())
result = GetLanIp();
return result;
}
}
///
/// 获取Web客户端的Ip
///
///
private static string GetWebClientIp()
{
var ip = GetWebRemoteIp();
foreach (var hostAddress in Dns.GetHostAddresses(ip))
{
if (hostAddress.AddressFamily == AddressFamily.InterNetwork)
return hostAddress.ToString();
}
return string.Empty;
}
public static string GetWebRemoteIp()
{
string remoteIp = null;
// Get the IP address of the client making the request
if (WebUtil.HttpContext.Request.Headers["X-Forwarded-For"] != "")
{
string[] forwardedFor = WebUtil.HttpContext.Request.Headers["X-Forwarded-For"].ToString().Split(',');
if (forwardedFor.Length > 0)
{
remoteIp = forwardedFor[forwardedFor.Length - 1];
}
}
else
{
//remoteIp = WebUtil.HttpContext.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
// Use the HTTP_X_FORWARDED_FOR environment variable
remoteIp = WebUtil.HttpContext.Request.Headers["HTTP_X_FORWARDED_FOR"];
}
return remoteIp;
}
///
/// 获取局域网IP
///
///
private static string GetLanIp()
{
foreach (var hostAddress in Dns.GetHostAddresses(Dns.GetHostName()))
{
if (hostAddress.AddressFamily == AddressFamily.InterNetwork)
return hostAddress.ToString();
}
return string.Empty;
}
#endregion
#region Host(获取主机名)
///
/// 获取主机名
///
public static string Host
{
get
{
return WebUtil.HttpContext == null ? Dns.GetHostName() : GetWebClientHostName();
}
}
public string GetClientHostName()
{
string hostname = "";
if (WebUtil.HttpContext.Request.Headers.ContainsKey("X-Forwarded-Host"))
{
hostname = WebUtil.HttpContext.Request.Headers["X-Forwarded-Host"];
}
else
{
hostname = WebUtil.HttpContext.Request.Host.Host;
}
return hostname;
}
///
/// 获取Web客户端主机名
///
///
private static string GetWebClientHostName()
{
var ip = GetWebRemoteIp();
var result = Dns.GetHostEntry(IPAddress.Parse(ip)).HostName;
if (result == "localhost.localdomain")
result = Dns.GetHostName();
return result;
}
#endregion
#region Browser(获取浏览器信息)
///
/// 获取浏览器信息
///
//public static string Browser
//{
// get
// {
// if (WebUtil.HttpContext == null)
// return string.Empty;
// var browser = WebUtil.HttpContext.Request.Browser;
// return string.Format("{0} {1}", browser.Browser, browser.Version);
// }
//}
#endregion
}
}