当前位置:首页 > C#教程 > C#高级

C#获取IP和整数IP方法

体验: 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/16string result = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
17if (null == result || result == String.Empty)
18{
19 result = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
20}
21if (null == result || result == String.Empty)
22{
23 result = HttpContext.Current.Request.UserHostAddress;
24}
25return result;
26}
2728publicstaticbool HvtIsIP(string ip)
29{
30return Regex.IsMatch(ip, @"^((23[0-3]|1d{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}
3233///<summary>34/// 把IP地址转为整数 hovertree.com
35///</summary>36///<param name="ip"></param>37///<returns></returns>38publicstaticlong HvtIpToLong(string ip)
39{
40char[] separator = newchar[] { . };
41string[] items = ip.Split(separator);
42returnlong.Parse(items[0]) << 2443 | long.Parse(items[1]) << 1644 | long.Parse(items[2]) << 845 | long.Parse(items[3]);
46}
4748///<summary>49/// 把整数转为IP 何问起
50///</summary>51///<param name="ipLong"></param>52///<returns></returns>53publicstaticstring HvtLongToIp(long ipLong)
54 {//http://hovertree.com/hvtart/bjae/cn5qrmxw.htm55 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);
60return sb.ToString();
61}
62 }

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

技术分享

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

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

原文:http://www.cnblogs.com/sosoft/p/zhengshuip.html


【说明】本文章由站长整理发布,文章内容不代表本站观点,如文中有侵权行为,请与本站客服联系(QQ:254677821)!