我正在编写使用 Windows IP Helper API 的 C# 代码。我试图调用的功能之一是“获取最佳界面“它采用 IP 的“uint”表示。我需要的是解析 IP 的文本表示以创建“uint”表示。

我通过谷歌找到了一些例子,比如 这个 或者 这个, ,但我非常确定应该有一种标准方法可以使用 .NET 实现此目的。唯一的问题是,我找不到这种标准方法。IPAddress.Parse 似乎是在正确的方向,但它不提供任何获得“uint”表示的方法......

还有一种方法可以使用 IP Helper 来执行此操作,即使用 解析网络字符串, ,但同样,我宁愿使用 .NET - 我相信对 pInvoke 的依赖越少越好。

那么,有人知道在 .NET 中执行此操作的标准方法吗?

有帮助吗?

解决方案

微软软件定义网络 IPAddress.Address 属性(返回 IP 地址的数字表示形式)已过时,您应该使用 获取地址字节 方法。

您可以使用以下代码将 IP 地址转换为数值:

var ipAddress = IPAddress.Parse("some.ip.address");
var ipBytes = ipAddress.GetAddressBytes();
var ip = (uint)ipBytes [3] << 24;
ip += (uint)ipBytes [2] << 16;
ip += (uint)ipBytes [1] <<8;
ip += (uint)ipBytes [0];

编辑:
正如其他评论者注意到的那样,上述代码仅适用于 IPv4 地址。IPv6 地址是 128 位长,因此不可能按照问题作者的要求将其转换为“uint”。

其他提示

不应该是:

var ipAddress = IPAddress.Parse("some.ip.address");
var ipBytes = ipAddress.GetAddressBytes();
var ip = (uint)ipBytes [0] << 24;
ip += (uint)ipBytes [1] << 16;
ip += (uint)ipBytes [2] <<8;
ip += (uint)ipBytes [3];

?

var ipuint32 = BitConverter.ToUInt32(IPAddress.Parse("some.ip.address.ipv4").GetAddressBytes(), 0);`

该解决方案比手动位移位更容易阅读。

如何在 C# 中将 IPv4 地址转换为整数?

你还应该记住 IPv4IPv6 长度不同。

不鼓励使用字节算术,因为它依赖于所有 IP 均为 4 个八位字节。

System.Net.IPAddress ipAddress = System.Net.IPAddress.Parse("192.168.1.1");

byte[] bytes = ipAddress.GetAddressBytes();
for (int i = 0; i < bytes.Length ; i++)
       Console.WriteLine(bytes[i]);

输出将为192 168 1 1

我从未找到一个干净的解决方案(即:.NET Framework 中的类/方法)解决此问题。我想除了您提供的解决方案/示例或 Aku 的示例之外,它是不可用的。:(

完整的解决方案:

public static uint IpStringToUint(string ipString)
{
    var ipAddress = IPAddress.Parse(ipString);
    var ipBytes = ipAddress.GetAddressBytes();
    var ip = (uint)ipBytes [0] << 24;
    ip += (uint)ipBytes [1] << 16;
    ip += (uint)ipBytes [2] <<8;
    ip += (uint)ipBytes [3];
    return ip;
}

public static string IpUintToString(uint ipUint)
{
    var ipBytes = BitConverter.GetBytes(ipUint);
    var ipBytesRevert = new byte[4];
    ipBytesRevert[0] = ipBytes[3];
    ipBytesRevert[1] = ipBytes[2];
    ipBytesRevert[2] = ipBytes[1];
    ipBytesRevert[3] = ipBytes[0];
    return new IPAddress(ipBytesRevert).ToString();
}

字节逆序:

public static uint IpStringToUint(string ipString)
{
    return BitConverter.ToUInt32(IPAddress.Parse(ipString).GetAddressBytes(), 0);
}

public static string IpUintToString(uint ipUint)
{
    return new IPAddress(BitConverter.GetBytes(ipUint)).ToString();
}

您可以在这里测试:

https://www.browserling.com/tools/dec-to-ip

http://www.smartconversion.com/unit_conversion/IP_Address_Converter.aspx

http://www.silisoftware.com/tools/ipconverter.php

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top