I'm looking for a function that will convert a standard IPv4 address into an Integer. Bonus points available for a function that will do the opposite.
Solution should be in C#.
I'm looking for a function that will convert a standard IPv4 address into an Integer. Bonus points available for a function that will do the opposite.
Solution should be in C#.
Assembled several of the above answers into an extension method that handles the Endianness of the machine and handles IPv4 addresses that were mapped to IPv6.
Unit tests:
32-bit unsigned integers are IPv4 addresses. Meanwhile, the
IPAddress.Address
property, while deprecated, is an Int64 that returns the unsigned 32-bit value of the IPv4 address (the catch is, it's in network byte order, so you need to swap it around).For example, my local google.com is at
64.233.187.99
. That's equivalent to:And indeed, http://1089059683/ works as expected (at least in Windows, tested with IE, Firefox and Chrome; doesn't work on iPhone though).
Here's a test program to show both conversions, including the network/host byte swapping:
I think this is wrong: "65536" ==> 0.0.255.255" Should be: "65535" ==> 0.0.255.255" or "65536" ==> 0.1.0.0"
Assuming you have an IP Address in string format (eg. 254.254.254.254)
As noone posted the code that uses
BitConverter
and actually checks the endianness, here goes:and back:
@Davy Ladman your solution with shift are corrent but only for ip starting with number less or equal 99, infact first octect must be cast up to long.
Anyway convert back with long type is quite difficult because store 64 bit (not 32 for Ip) and fill 4 bytes with zeroes
Enjoy!
Massimo