C#中如何将IP地址转变成UInt类型

C#中如何将IP地址转变成UInt类型?比如192.168.23.25转换成UInt类型

在 C# 中,可以使用 System.Net.IPAddress.Parse 方法将 IP 地址转换为 System.Net.IPAddress 类型,然后使用 IPAddress.GetAddressBytes 方法获取 IP 地址的字节数组,最后将字节数组转换为 uint 类型。以下是将 IP 地址转换为 uint 类型的代码示例:

using System;
using System.Net;

class Program {
    static void Main(string[] args) {
        string ipAddressString = "192.168.23.25";
        IPAddress ipAddress = IPAddress.Parse(ipAddressString);
        byte[] ipBytes = ipAddress.GetAddressBytes();
        uint ipAddressUint = BitConverter.ToUInt32(ipBytes, 0);
        Console.WriteLine(ipAddressUint);
    }
}


在上面的示例中,首先将 IP 地址字符串转换为 System.Net.IPAddress 类型,然后使用 GetAddressBytes 方法获取字节数组,最后使用 BitConverter.ToUInt32 方法将字节数组转换为 uint 类型。注意,转换的结果将会是网络字节顺序(big-endian)的 uint 值,如果需要转换为主机字节顺序(little-endian)的值,可以使用 IPAddress.NetworkToHostOrder 方法。