IP Address to Integer Conversion in C# (and other languages)
A couple of times, I’ve needed a function to convert a string representation of an IP address to a 32-bit unsigned integer, to save in a database for example. It’s kind of a waste to save the string representation of an IP address in a database, as IPv4 addresses are only 32 bits and fit nicely in a 32-bit unsigned integer field of, for example, a MySQL table. Each character in the string would be a byte!
I’ve had to do this in lots of languages, but the source here is in C#. The approach is similar for other languages. Each octet of the IP address is 8 bits, so we start an accumulator at 0, XOR with the first bit, shift the accumulator left 8 bits, rinse, repeat.
Pretty compact. I’ve mostly used this for getting the 32-bit unsigned integer representation of the running machine, so I pull the string IPAddress off the network card in a normal fashion (maybe like so or so or resolve anything like so).
Popularity: 73%
5 Comments »
Comment by inanc
March 3, 2007 @ 3:33 pm #
Good advice but wasn’t there a framework support to this?
Comment by Billy
March 4, 2007 @ 2:56 pm #
Always possible, but I couldn’t find anything. If you do, please feel free to share…
Comment by Debjit
July 23, 2007 @ 9:25 am #
Good
Comment by omatase
October 3, 2007 @ 5:45 pm #
Here is a way to do it with built-in libraries.
IPAddress ip = IPAddress.Parse(”127.0.0.1″);
int asInteger = BitConverter.ToInt32(ip.GetAddressBytes(), 0);
Comment by omatase
October 3, 2007 @ 7:14 pm #
looks like you have to reverse the array for BitConverter to calculate it correctly.
RSS feed for comments on this post. TrackBack URI
Leave a comment