如何在 C# 中将 IP 地址字符串解析为 uint 值?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/36831/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-03 09:44:05  来源:igfitidea点击:

How do you parse an IP address string to a uint value in C#?

提问by Hershi

I'm writing C# code that uses the windows IP Helper API. One of the functions I'm trying to call is "GetBestInterface" that takes a 'uint' representation of an IP. What I need is to parse a textual representation of the IP to create the 'uint' representation.

我正在编写使用 Windows IP Helper API 的 C# 代码。我试图调用的函数之一是“ GetBestInterface”,它采用 IP 的“uint”表示。我需要的是解析 IP 的文本表示以创建“uint”表示。

I've found some examples via Google, like this oneor this one, but I'm pretty sure there should be a standard way to achieve this with .NET. Only problem is, I can't find this standard way. IPAddress.Parse seems to be in the right direction, but it doesn't supply any way of getting a 'uint' representation...

我通过 Google 找到了一些示例,例如this onethis one,但我很确定应该有一种标准方法可以使用 .NET 实现这一点。唯一的问题是,我找不到这种标准方式。IPAddress.Parse 似乎是在正确的方向,但它不提供任何方式获得 'uint' 表示......

There is also a way of doing this using IP Helper, using the ParseNetworkString, but again, I'd rather use .NET - I believe the less I rely on pInvoke the better.

还有一种使用 IP Helper 的方法,使用ParseNetworkString,但同样,我宁愿使用 .NET - 我相信我越少依赖 pInvoke 越好。

So, anyone knows of a standard way to do this in .NET?

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

采纳答案by aku

MSDN saysthat IPAddress.Address property (which returns numeric representation of IP address) is obsolete and you should use GetAddressBytesmethod.

MSDNIPAddress.Address 属性(返回 IP 地址的数字表示)已过时,您应该使用GetAddressBytes方法。

You can convert IP address to numeric value using following code:

您可以使用以下代码将 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];

EDIT:
As other commenters noticed above-mentioned code is for IPv4 addresses only. IPv6 address is 128 bits long so it's impossible to convert it to 'uint' as question's author wanted.

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

回答by Andrei R?nea

I have never found a clean solution (i.e.: a class / method in the .NET Framework) for this problem. I guess it just isn't available except the solutions / examples you provided or Aku's example. :(

我从来没有为这个问题找到一个干净的解决方案(即:.NET 框架中的类/方法)。我想除了您提供的解决方案/示例或 Aku 的示例之外,它不可用。:(

回答by Dmitry Shechtman

Byte arithmetic is discouraged, as it relies on all IPs being 4-octet ones.

不鼓励使用字节算术,因为它依赖于所有 IP 都是 4 字节的 IP。

回答by Corin Blaikie

Also you should remember that IPv4and IPv6are different lengths.

您还应该记住IPv4IPv6的长度不同。

回答by nimish

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

This solution is easier to read than manual bit shifting.

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

See How to convert an IPv4 address into a integer in C#?

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

回答by Christo

Shouldn't it be:

不应该是:

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];

?

?

回答by qasali

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]);

Output will be 192 168 1 1

输出将是 192 168 1 1

回答by Pavel Samoylenko

Complete solution:

完整的解决方案:

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();
}

Reverse order of bytes:

字节顺序相反:

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();
}

You can test here:

你可以在这里测试:

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

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

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

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

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

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

回答by Nick

Correct solution that observes Endianness:

观察字节序的正确解决方案:

var ipBytes = ip.GetAddressBytes();
ulong ip = 0;
if (BitConverter.IsLittleEndian)
{
    ip = (uint) ipBytes[0] << 24;
    ip += (uint) ipBytes[1] << 16;
    ip += (uint) ipBytes[2] << 8;
    ip += (uint) ipBytes[3];
}
else
{
    ip = (uint)ipBytes [3] << 24;
    ip += (uint)ipBytes [2] << 16;
    ip += (uint)ipBytes [1] <<8;
    ip += (uint)ipBytes [0];
}