首页 > 代码库 > C# IP地址与数字之间的互转

C# IP地址与数字之间的互转

技术分享

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;

namespace ip2Long
{
    class Program
    {
        static void Main(string[] args)
        {
            //首先,输入一个标准的IP地址 例如 192.168.1.1
            Console.WriteLine("请输入一个标准的IP地址 例如 192.168.1.1");
            //接收用户输入的数据
            string ip = Console.ReadLine();
            string IntIp = ipToLong(ip);
            Console.WriteLine(string.Format("IP  {0} 地址 转换后结果 :{1}", ip, IntIp));
            IntIp = ipToLong(ip);
            Console.WriteLine(string.Format("IP2  {0} 地址 转换后结果 :{1}", ip, IntIp));
            ip = LongToip(IntIp);
            Console.WriteLine(string.Format("数字 {0}  转换后IP地址结果 :{1}", IntIp, ip));
            Console.ReadKey();

        }
        /// <summary>
        /// IP地址转换为数字
        /// </summary>
        /// <param name="ip">ip地址</param>
        /// <returns></returns>
        static string ipToLong(string ip)
        {
            long IntIp = 0;
            string[] ips = ip.Split(.);
            IntIp = long.Parse(ips[0]) << 0x18 | long.Parse(ips[1]) << 0x10 | long.Parse(ips[2]) << 0x8 | long.Parse(ips[3]);
            return IntIp.ToString();

        }
        /// <summary>
        /// C# 简单的写法
        /// </summary>
        /// <param name="ip"></param>
        /// <returns></returns>
        static string ipToLong2(string ip)
        {
            IPAddress ipaddress = IPAddress.Parse(ip);
            byte[] addbuffer = ipaddress.GetAddressBytes();
            Array.Reverse(addbuffer);
            return System.BitConverter.ToUInt64(addbuffer, 0).ToString();
        }
        /// <summary>
        /// IP地址转换为数字
        /// </summary>
        /// <param name="ip">ip地址</param>
        /// <returns></returns>
        static string LongToip(string ip)
        {
            long IntIp = long.Parse(ip);
            StringBuilder sb = new StringBuilder();
            sb.Append(IntIp >> 0x18 & 0xff).Append(".");
            sb.Append(IntIp >> 0x10 & 0xff).Append(".");
            sb.Append(IntIp >> 0x8 & 0xff).Append(".");
            sb.Append(IntIp & 0xff);
            return sb.ToString();

        }
    }
}

 

C# IP地址与数字之间的互转