Monday, July 20, 2009

converting IP address to IP number

Ip number is a numerical representation of the ip address we are all used to .
For instance 1.2.3.4 = 1690960 ;

It is good for some reasons, like conveting the Ip address to geographical position, or rule manupulation like firewalls and network devices.

How do you do that ?

Here is a little method that shows how to do that in c #

public static uint convertIP(string sIp)
{
string[] sOctecs;
char[] cSeperator = { '.' };
int[] iOctet = new int[4];
uint iReturnIPNumber = 0;
if (sIp != "")
{
bool bConvertOK;
sOctecs = sIp.Split(cSeperator, 4);//split the string to the octets
for (int i = 0; i <>
{
bConvertOK = int.TryParse(sOctecs[i], out iOctet[i]);
if (!bConvertOK)
{
return 0;
}
}//end for
// iOctecs contain integers , lets do the magic

//some math
iReturnIPNumber = (uint)iOctet[3];
iReturnIPNumber = iReturnIPNumber + ((uint)iOctet[2] * (uint)256);
iReturnIPNumber = iReturnIPNumber + ((uint)iOctet[1] * (uint)256 * (uint)256);
iReturnIPNumber = iReturnIPNumber + ((uint)iOctet[0] * (uint)256 * (uint)256 * (uint)256);

}
return iReturnIPNumber;
}


If you need it in the database , then mySQL has a built in functions of converting

mysql> SELECT INET_ATON('192.168.10.50');
+----------------------------+
| INET_ATON('192.168.10.50') |
+----------------------------+
| 3232238130 |
+----------------------------+
1 row in set (0.00 sec)

mysql> SELECT INET_NTOA(839559360);
+----------------------+
| INET_NTOA(839559360) |
+----------------------+
| 50.10.168.192 |
+----------------------+
1 row in set (0.00 sec)

1 comment:

  1. Or of course you can use the built-in methods, something like this:

    var ipuint32 = BitConvertor.ToUInt32(IPAddress.Parse("127.0.0.1").GetAddressBytes());

    (just need to check byte-order and IPv4/IPv6 issues)

    ReplyDelete