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#.
With the UInt32 in the proper little-endian format, here are two simple conversion functions:
To convert from IPv4 to correct integer:
And to convert back:
Explanation:
IP addresses are in network order (big-endian), while
int
s are little-endian on Windows, so to get a correct value, you must reverse the bytes before converting.Also, even for
IPv4
, anint
can't hold addresses bigger than127.255.255.255
, e.g. the broadcast address(255.255.255.255)
, so use auint
.