格古洛

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

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: :: 管理 ::
  5 随笔 :: 2 文章 :: 8 评论 :: 11958 阅读
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

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   格古洛  阅读(650)  评论(0编辑  收藏  举报
编辑推荐:
· .NET制作智能桌面机器人:结合BotSharp智能体框架开发语音交互
· 软件产品开发中常见的10个问题及处理方法
· .NET 原生驾驭 AI 新基建实战系列:向量数据库的应用与畅想
· 从问题排查到源码分析:ActiveMQ消费端频繁日志刷屏的秘密
· 一次Java后端服务间歇性响应慢的问题排查记录
阅读排行:
· 互联网不景气了那就玩玩嵌入式吧,用纯.NET开发并制作一个智能桌面机器人(四):结合BotSharp
· Vite CVE-2025-30208 安全漏洞
· 《HelloGitHub》第 108 期
· MQ 如何保证数据一致性?
· 一个基于 .NET 开源免费的异地组网和内网穿透工具
点击右上角即可分享
微信分享提示