本文主要介绍了C# 获取IP及判断IP是否在区间的方法。具有很好的参考价值,下面跟着小编一起来看下吧
话不多说,请看代码:
/// <summary>
/// 获取客户端IP
/// </summary>
/// <returns></returns>
public static string GetClientIpAddress()
{
var httpContext = HttpContext.Current;
if (httpContext.Request.ServerVariables == null)
{
return null;
}
var clientIp = httpContext.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] ?? httpContext.Request.ServerVariables["REMOTE_ADDR"];
try
{
foreach (var hostAddress in Dns.GetHostAddresses(clientIp))
{
if (hostAddress.AddressFamily == AddressFamily.InterNetwork)
{
return hostAddress.ToString();
}
}
foreach (var hostAddress in Dns.GetHostAddresses(Dns.GetHostName()))
{
if (hostAddress.AddressFamily == AddressFamily.InterNetwork)
{
return hostAddress.ToString();
}
}
}
catch (Exception ex)
{
}
return clientIp;
}
/// <summary>
/// ip是否在ip空间内
/// </summary>
/// <param name="ip"></param>
/// <param name="ipSection"></param>
/// <returns></returns>
public static Boolean ipExistsInRange(String ip, String ipSection)
{
ipSection = ipSection.Trim();
ip = ip.Trim();
int idx = ipSection.IndexOf('-');
String beginIP = ipSection.Substring(0, idx);
String endIP = ipSection.Substring(idx + 1);
return getIp2long(beginIP) <= getIp2long(ip) && getIp2long(ip) <= getIp2long(endIP);
}
public static long getIp2long(String ip)
{
ip = ip.Trim();
String[] ips = ip.Split('.');
long ip2long = 0L;
for (int i = 0; i < 4; ++i)
{
ip2long = ip2long << 8 | Int64.Parse(ips[i]);
}
return ip2long;
}
public static long getIp2long2(String ip)
{
ip = ip.Trim();
String[] ips = ip.Split('.');
long ip1 = Int64.Parse(ips[0]);
long ip2 = Int64.Parse(ips[1]);
long ip3 = Int64.Parse(ips[2]);
long ip4 = Int64.Parse(ips[3]);
long ip2long = 1L * ip1 * 256 * 256 * 256 + ip2 * 256 * 256 + ip3 * 256 + ip4;
return ip2long;
}
以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,同时也希望多多支持编程学习网!
织梦狗教程
本文标题为:C# 获取IP及判断IP是否在区间


基础教程推荐
猜你喜欢
- C#调用摄像头实现拍照功能的示例代码 2023-03-09
- C#获取指定目录下某种格式文件集并备份到指定文件夹 2023-05-30
- C#中的Linq to JSON操作详解 2023-06-08
- 实例详解C#实现http不同方法的请求 2022-12-26
- C#中 Json 序列化去掉null值的方法 2022-11-18
- C# 解析XML和反序列化的示例 2023-04-14
- C#通过标签软件Bartender的ZPL命令打印条码 2023-05-16
- Unity 如何获取鼠标停留位置下的物体 2023-04-10
- c# – USING块在网站与Windows窗体中的行为不同 2023-09-20
- Unity shader实现高斯模糊效果 2023-01-16