你如何解析的IP地址字符串在C#中的单元值? [英] How do you parse an IP address string to a uint value in C#?

查看:432
本文介绍了你如何解析的IP地址字符串在C#中的单元值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在写使用Windows IP助手API的C#代码。其中一个我想调用的函数是GetBestInterface接受一个I​​P的UINT表示。我需要的是解析IP的文本表示创建UINT表示。

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.

我发现通过谷歌的一些例子,喜欢的这一个或这一个,但我敢肯定应该有使用.NET来实现这一标准的方式。唯一的问题是,我无法找到这种标准方式。 IPAddress.Parse似乎是在正确的方向,但它并没有提供得到一个UINT表示任何方式...

I've found some examples via Google, like this one or 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...

还有一种方式这样使用IP助手,使用ParseNetworkString ,但同样,我宁愿使用.NET - 我相信我靠的PInvoke越少越好

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.

因此,任何人在.NET中做到这一点的标准方式知道

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

推荐答案

MSDN的says 的IPAddress.Address属性(返回的IP地址的数字表示)是过时的,你应该使用< A HREF =http://msdn.microsoft.com/en-us/library/system.net.ipaddress.getaddressbytes.aspx> GetAddressBytes 方法。

MSDN says that IPAddress.Address property (which returns numeric representation of IP address) is obsolete and you should use GetAddressBytes method.

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

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

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作为问题的作者想要的。


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.

这篇关于你如何解析的IP地址字符串在C#中的单元值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆