Converting IP To Numeric

When looking up a Geo IP, you will need to convert the IP address to numeric value.  Below shows the formula for the transformation in both directions.

Given IP address is: w.x.y.z

Numeric:

256^3(w) + 256^2(x) + 256(y) + z

or

16777216(w) + 65536(x) + 256(y) + z

IP:

w = (int)( IP Number / 16777216 ) % 256 
x = (int)( IP Number / 65536 ) % 256 
y = (int)( IP Number / 256 ) % 256 
z = (int)( IP Number ) % 256

Doing this in .NET would yield the following code:

public static uint? IPToNumeric(string address)
{
string[] splits = address.Split('.');
if (splits.Length == 4)
{
try
{
return
16777216 * uint.Parse(splits[0]) +
65536 * uint.Parse(splits[1]) +
256 * uint.Parse(splits[2]) +
uint.Parse(splits[3]);
}
catch { }
}
return null;
}

public static string NumericToIP(uint numeric)
{
try
{
return string.Format("{0}.{1}.{2}.{3}",
(uint)(numeric / 16777216) % 256,
(uint)(numeric / 65536) % 256,
(uint)(numeric / 256) % 256,
numeric % 256);
}
catch { }
return null;
}

No comments: