Search
Close this search box.

Convert IP to Long and Vice Versa C#

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:
}

Print | posted @ Wednesday, April 29, 2009 11:16 AM

This article is part of the GWB Archives. Original Author: Rohit Gupta

Related Posts