Rohit Gupta

Engaging talk on Microsoft Technologies ....My Resume

  Home  |   Contact  |   Syndication    |   Login
  39 Posts | 0 Stories | 52 Comments | 0 Trackbacks

News



Twitter












Archives

Image Galleries

Personal

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: }
  • Share This Post:
  • Share on Twitter
  • Share on Facebook
  • Share on Technorati
posted on Wednesday, April 29, 2009 11:16 AM

Feedback

# re: Convert IP to Long and Vice Versa C# 12/10/2009 7:14 PM alla
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 ) );

# re: Convert IP to Long and Vice Versa C# 4/24/2011 10:29 AM heasy
The last suggestion of alla was deprecated in last versions.

Post A Comment
Title:
Name:
Email:
Website:
Comment:
Verification: