web .net 获取Ip地址工具类

这个是B/S,后台获取本机Ip地址相关的工具类,代码如下:

public class NetUtil
{
    //获取IP地址
    public static string Ip
    {
        get
        {
            string str = null;
            if (HttpContext.Current != null)
                str = GetWebClientIp();
            if (string.IsNullOrEmpty(str))
                str = GetLanIp();
            return str;
        }
    }
    private static string GetWebClientIp()
    {
        foreach (IPAddress hostAddress in Dns.GetHostAddresses(GetWebRemoteIp()))
        {
            if (hostAddress.AddressFamily == AddressFamily.InterNetwork)
                return hostAddress.ToString();
        }
        return string.Empty;
    }
    private static string GetWebRemoteIp()
    {
        return HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] ?? HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
    }
    private static string GetLanIp()
    {
        foreach (IPAddress hostAddress in Dns.GetHostAddresses(Dns.GetHostName()))
        {
            if (hostAddress.AddressFamily == AddressFamily.InterNetwork)
                return hostAddress.ToString();
        }
        return string.Empty;
    }
    public static string Host
    {
        get
        {
            return HttpContext.Current == null ? Dns.GetHostName() : GetWebClientHostName();
        }
    }
    private static string GetWebClientHostName()
    {
        if (!HttpContext.Current.Request.IsLocal)
            return string.Empty;
        string hostName = Dns.GetHostEntry(IPAddress.Parse(GetWebRemoteIp())).HostName;
        if (hostName == "localhost.localdomain")
            hostName = Dns.GetHostName();
        return hostName;
    }
    public static string Browser
    {
        get
        {
            if (HttpContext.Current == null)
                return string.Empty;
            HttpBrowserCapabilities browser = HttpContext.Current.Request.Browser;
            return string.Format("{0} {1}", (object)browser.Browser, (object)browser.Version);
        }
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容