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

后端 未结 9 733
庸人自扰
庸人自扰 2020-12-30 13:44

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

相关标签:
9条回答
  • 2020-12-30 14:16

    Also you should remember that IPv4 and IPv6 are different lengths.

    0 讨论(0)
  • 2020-12-30 14:17
    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#?

    0 讨论(0)
  • 2020-12-30 14:19

    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.

    0 讨论(0)
提交回复
热议问题