Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 603
Hershi Avatar asked Aug 31 '08 12:08

Hershi


2 Answers

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

?

like image 72
Christo Avatar answered Nov 16 '22 21:11

Christo


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

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

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.

like image 30
aku Avatar answered Nov 16 '22 21:11

aku