格古洛

记下遇到的一些问题,或许以后还用得着

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: :: 管理 ::

using System;
using System.Net;

namespace Server.Core
{
    /// <summary>
    /// IP地址与长整型数字的互换算法
    /// </summary>
    public static class IPExtention
    {
        /// <summary>
        /// IP地址转换成长整型数字
        /// </summary>
        /// <param name="src">数据源</param>
        /// <returns>长整型数字</returns>
        public static string GetIPValue(this string src)
        {
            int x = 3;
            long result = 0;

            IPAddress ip = null;

            if (!IPAddress.TryParse(src, out ip))
            {
                throw new InvalidCastException("ip格式无效");
            }
            foreach (byte b in ip.GetAddressBytes())
            {
                result += (long)b << 8 * x--;
            }
            return result.ToString();
        }

        /// <summary>
        /// 长整型数字转成IP地址
        /// </summary>
        /// <param name="src">数据源</param>
        /// <returns>IP地址</returns>
        public static string GetIPString(this string src)
        {
            long ipValue = 0;
            string result = string.Empty;

            if (!long.TryParse(src, out ipValue))
            {
                throw new InvalidCastException("ip格式无效");
            }
            byte[] bytes = new byte[4];

            for (int i = 0; i < 4; i++)
            {
                bytes[i] = (byte)(ipValue >> 8 * (3 - i) & 255);
            }
            try
            {
                result = new IPAddress(bytes).ToString();
                return result;
            }
            catch
            {
                throw new InvalidCastException("ip格式无效");
            }
        }
    }
}

posted on 2013-08-14 10:55  格古洛  阅读(644)  评论(0编辑  收藏  举报