C#获取IP和整数IP方法

本文介绍了一种用于获取客户端真实IP地址的方法,并提供了IP地址与整数之间的转换技术。通过C#实现,适用于ASP.NET环境。文章还包含正则表达式验证IP地址的有效性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

体验: http://tool.hovertree.com/info/ip/

代码如下:
 1 using System;
 2 using System.Text;
 3 using System.Text.RegularExpressions;
 4 using System.Web;
 5 
 6 namespace HoverTree.HoverTreeFrame.HvtNet
 7 {
 8 public class HoverTreeIP
 9 {
10 /// <summary>
11 /// 获取真实IP
12 /// </summary>
13 /// <returns></returns>
14 public static string GetHoverTreeIp()
15 {//http://tool.hovertree.com/info/ip/
16 string result = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
17 if (null == result || result == String.Empty)
18 {
19 result = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
20 }
21 if (null == result || result == String.Empty)
22 {
23 result = HttpContext.Current.Request.UserHostAddress;
24 }
25 return result;
26 }
27 
28 public static bool HvtIsIP(string ip)
29 {
30 return Regex.IsMatch(ip, @"^((23[0-3]|1\d{2}|[1-9]\d|[1-9])\.)((25[0-5]|2[0-4]\d|1?\d{1,2})\.){2}((25[0-5]|2[0-4]\d|1?\d{1,2}))$") ;
31 }
32 
33 /// <summary>
34 /// 把IP地址转为整数 hovertree.com
35 /// </summary>
36 /// <param name="ip"></param>
37 /// <returns></returns>
38 public static long HvtIpToLong(string ip)
39 {
40 char[] separator = new char[] { '.' };
41 string[] items = ip.Split(separator);
42 return long.Parse(items[0]) << 24
43 | long.Parse(items[1]) << 16
44 | long.Parse(items[2]) << 8
45 | long.Parse(items[3]);
46 }
47 
48 /// <summary>
49 /// 把整数转为IP 何问起
50 /// </summary>
51 /// <param name="ipLong"></param>
52 /// <returns></returns>
53 public static string HvtLongToIp(long ipLong)
54 {//http://hovertree.com/hvtart/bjae/cn5qrmxw.htm
55 StringBuilder sb = new StringBuilder();
56 sb.Append((ipLong >> 24) & 0xFF).Append(".");
57 sb.Append((ipLong >> 16) & 0xFF).Append(".");
58 sb.Append((ipLong >> 8) & 0xFF).Append(".");
59 sb.Append(ipLong & 0xFF);
60 return sb.ToString();
61 }
62 }

类的代码将发布在HoverTreeCMS项目中。

山水画

ASP.NET开源CMS http://www.cnblogs.com/sosoft/p/cms.html

开发技术文章收集 http://www.cnblogs.com/sosoft/p/kaifajishu.html

转载于:https://www.cnblogs.com/sosoft/p/zhengshuip.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值