Geeks With Blogs
Rohit Gupta Engaging talk on Microsoft Technologies ....My Resume

The inbuilt function in System.Net.IPAddress(IPAddr).ToString() method returns IP’s in the reverse order, hence I had to look for alternatives. Here is the correct version to convert IP address to long and viceversa

   1: static public string LongToIP(long longIP)
   2: {
   3:     string ip = string.Empty;
   4:     for (int i = 0; i < 4; i++)
   5:     {
   6:         int num = (int)(longIP / Math.Pow(256, (3 - i)));
   7:         longIP = longIP - (long)(num * Math.Pow(256, (3 - i)));
   8:         if (i == 0)
   9:             ip = num.ToString();
  10:         else
  11:             ip  = ip + "." + num.ToString();
  12:     }
  13:     return ip;
  14: }
  15:  
  16: public static long IP2Long(string ip)
  17: {
  18:     string[] ipBytes;
  19:     double num = 0;
  20:     if(!string.IsNullOrEmpty(ip))
  21:     {
  22:         ipBytes = ip.Split('.');
  23:         for (int i = ipBytes.Length - 1; i >= 0; i--)
  24:         {
  25:             num += ((int.Parse(ipBytes[i]) % 256) * Math.Pow(256, (3 - i)));
  26:         }
  27:     }
  28:     return (long)num;
  29: }
Posted on Wednesday, April 29, 2009 11:16 AM | Back to top


Comments on this post: Convert IP to Long and Vice Versa C#

# re: Convert IP to Long and Vice Versa C#
Requesting Gravatar...
I suggest other versions:

static public string long2ip( long longIP )
{
return new IPAddress( longIP ).ToString();
}

static public long ip2long( string ip )
{
return IPAddress.Parse( ip ).Address;
}

> The inbuilt function in System.Net.IPAddress(IPAddr).ToString() method returns IP’s in the reverse order

You can use IPAddress.NetworkToHostOrder() static members to change bytes order if you work with 'network'-odered addresses:

string ip = long2ip( IPAddress.NetworkToHostOrder( longIP ) );
Left by alla on Dec 10, 2009 7:14 PM

# re: Convert IP to Long and Vice Versa C#
Requesting Gravatar...
The last suggestion of alla was deprecated in last versions.
Left by heasy on Apr 24, 2011 10:29 AM

Your comment:
 (will show your gravatar)


Copyright © Rohit Gupta | Powered by: GeeksWithBlogs.net