Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
692 views
in Technique[技术] by (71.8m points)

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

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.

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...

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.

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...