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

posted @ 2016-12-13 14:39  wcgsir  阅读(278)  评论(0编辑  收藏  举报