How do you parse an IP address string to a uint value in C#?
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];
?
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.
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#?