zoukankan      html  css  js  c++  java
  • ASP.NET 的IP帮助类

    个人网站地址: https://www.lesg.cn/netdaima/net/2016-239.html

    ASP.NET 的IP帮助类

    在Web开发中会出现需要调用客户IP的方法; 一般调用方法就是使用Request函数来获取;

    代码如下

    HttpContext.Current.Request.UserHostAddress.ToString()

    不过想要放获取方法变得高大上一点的话还是得需要自己写一个IP帮助类;以下是代码

    public class IPHelp
    {
    #region IP地址互转整数
    /// <summary>
    /// 将IP地址转为整数形式
    /// </summary>
    /// <returns>整数</returns>
    public static long IP2Long(IPAddress ip)
    {
    int x = 3;
    long o = 0;
    foreach (byte f in ip.GetAddressBytes())
    {
    o += (long)f << 8 * x--;
    }
    return o;
    }
    /// <summary>
    /// 将整数转为IP地址
    /// </summary>
    /// <returns>IP地址</returns>
    public static IPAddress Long2IP(long l)
    {
    byte[] b = new byte[4];
    for (int i = 0; i < 4; i++)
    {
    b[3 - i] = (byte)(l >> 8 * i & 255);
    }
    return new IPAddress(b);
    }
    #endregion
    /// <summary>
    /// 获得客户端IP
    /// </summary>
    public static string ClientIP
    {
    get
    {
    bool isErr = false;
    string ip = "127.0.0.1";
    try
    {
     
    string[] temp;
    if (HttpContext.Current.Request.ServerVariables["HTTP_X_ForWARDED_For"] == null)
    ip = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"].ToString();
    else
    ip = HttpContext.Current.Request.ServerVariables["HTTP_X_ForWARDED_For"].ToString();
    if (ip.Length > 15)
    isErr = true;
    else
    {
    temp = ip.Split('.');
    if (temp.Length == 4)
    {
    for (int i = 0; i < temp.Length; i++)
    {
    if (temp[i].Length > 3) isErr = true;
    }
    }
    else
    isErr = true;
    }
    }
    catch { isErr = false; }
     
    if (isErr)
    return "1.1.1.1";
    else
    return ip;
    }
    }
    }

    需要调用来源IP的时候直接 调用ClientIP属性即可

    var ipaddr =IPHelp.ClientIP;

    代码下载地址:http://lesg.cn/downs/161209/IPHelp.zip

    原文地址:https://www.lesg.cn/netdaima/net/2016-239.html

  • 相关阅读:
    类型转换
    new Overload函数输出
    快捷键加入属性代码段
    xp 下 安装Ubuntu 11.04 双系统
    native2ascii 用法解析
    apusic jconsole jmx connecitons url
    oracle 分页
    几条最基本的 sqlplus命令
    windows下plsql 设置 里面timestamp显示的格式
    oracle 时间差 做查询条件
  • 原文地址:https://www.cnblogs.com/wcgsir/p/6169860.html
Copyright © 2011-2022 走看看