Store an IP Address in a human-readable Int64 (bigint)
September 29, 2009 by: B.HardingLets say you have an ip address in a string such as ”127.1.2.3″
This code will store the information in an int64 (C#) or bigint (SQL) in with three places per octet.
127001002003
The highest this number could go is 255,255,255,255.00 which is too large for a 32 bit integer. Hence the Int64. In SQL an 64 bit Integer is big int so that is what you’ll need to store in an MS-SQL Database.
I worked this up as a work-around on a project and present it here for your enjoyment.
using System.Text.RegularExpressions;
public static Int64 convertIP(string sAddress) {
Match ipaddress = Regex.Match(sAddress,“^([\\d]*).([\\d]*).([\\d]*).([\\d]*)”);
Int64 iAddress = 0;
Int64 ip1 =Convert.ToInt64(ipaddress.Groups[1].ToString()) * 1000000000;
Int64 ip2 =Convert.ToInt64(ipaddress.Groups[2].ToString()) * 1000000;
Int64 ip3 =Convert.ToInt64(ipaddress.Groups[3].ToString()) * 1000;
Int64 ip4 =Convert.ToInt64(ipaddress.Groups[4].ToString());
iAddress = ip1 + ip2 + ip3 + ip4;
return iAddress;
}
Extra credit: This number is now 127,001,002,003. You can use string formating to display it as 127.001.002.003 by using the format string N0 (Number, zero decimal places) and changing the number group separator from the default comma to a period. All with the raw int64, no function required.
Int64 iAddress = convertIP(Request.UserHostAddress);
Response.Write(iAddress).ToString(“N0″, new NumberFormatInfo { NumberGroupSeparator =“.” }));



Is it me or did this article make you want to buy an iPad?