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

平常我们的ip地址存入计算机并不是点分形式,而是uint32类型的。下面使用C#实现IP地址与数字之间的转换。

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

namespace Test3
{
    class Program
    {
        static void Main(string[] args)
        {
            //1.写出一个函数将IP地址字符串转成一个数字表示
            Console.WriteLine(IpToInt1("192.168.0.1"));
            Console.WriteLine(IpToInt2("192.168.0.1"));
            Console.WriteLine(IntToIp(3232235521));
        }

        //IP转数字
        static UInt32 IpToInt1(string ip)
        {
            IPAddress ipaddress = IPAddress.Parse(ip);
            byte[] addbuffer = ipaddress.GetAddressBytes();
            Array.Reverse(addbuffer);
            return System.BitConverter.ToUInt32(addbuffer, 0);
        }

        //IP转数字
        static long IpToInt2(string ip)
        {
            long intIp = 0;
            string[] ips = ip.Split('.');

            intIp = long.Parse(ips[0]) << 24 | long.Parse(ips[1]) << 16 | long.Parse(ips[2]) << 8 | long.Parse(ips[3]);
            return intIp;
        }
        
        //数字转化为IP
        static string IntToIp(long ipInt)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append((ipInt >> 24) & 0xFF).Append(".");
            sb.Append((ipInt >> 16) & 0xFF).Append(".");
            sb.Append((ipInt >> 8) & 0xFF).Append(".");
            sb.Append(ipInt & 0xFF);

            return sb.ToString();
        }
    }
}

转载自:https://www.cnblogs.com/testsec/p/6095832.html

猜你喜欢

转载自blog.csdn.net/qq_38721111/article/details/93501196
今日推荐