3

That does this calculation below

address = '174.36.207.186'

( o1, o2, o3, o4 ) = address.split('.')

integer_ip =   ( 16777216 * o1 )
             + (    65536 * o2 )
             + (      256 * o3 )
             +              o4
John Saunders
  • 160,644
  • 26
  • 247
  • 397
Furkan Gözükara
  • 22,964
  • 77
  • 205
  • 342
  • possible duplicate of [How to convert an IPv4 address into a integer in C#?](http://stackoverflow.com/questions/461742/how-to-convert-an-ipv4-address-into-a-integer-in-c) – Dan Abramov Dec 21 '12 at 22:12
  • Look [here](http://social.msdn.microsoft.com/Forums/en-US/netfxcompact/thread/00a001af-e01d-4590-82c1-1f6142eb8c34) – Jordão Dec 21 '12 at 22:13
  • i checked both place and did not find working solution. first of all it has to be int 64 not 32 – Furkan Gözükara Dec 21 '12 at 22:13
  • `Int32` would not support addresses larger than `127.255.255.255`; however, `UInt32` would support the full IPv4 range. `Int64` would be overkill. – Douglas Dec 21 '12 at 22:21
  • I think that the solution from @Douglas is far better than the duplicate signaled. Let this question and its answer open please – Steve Dec 21 '12 at 22:41
  • @Steve totally agree. those duplicates actually does not contain proper answer. – Furkan Gözükara Dec 21 '12 at 23:16

3 Answers3

7
string s = "174.36.207.186";

uint i = s.Split('.')
          .Select(uint.Parse)
          .Aggregate((a, b) => a * 256 + b);
Douglas
  • 53,759
  • 13
  • 140
  • 188
2

You can parse the numbers into a byte array, then use BitConverter.ToInt32 to put them together into an int:

byte[] parts = address.Split('.').Select(Byte.Parse).ToArray();
if (BitConverter.IsLittleEndian) {
  Array.Reverse(parts);
}
int ip = BitConverter.ToInt32(parts, 0);
Guffa
  • 687,336
  • 108
  • 737
  • 1,005
  • 1
    `Int32` only supports addresses up to `127.255.255.255`. – Douglas Dec 21 '12 at 22:22
  • @Douglas: Not at all. Addresses higher than that are represented as negative `int` values. You can cast the `int` it to `uint` if you like that better. – Guffa Dec 21 '12 at 23:39
  • Fair point. I should have said that the intent is less clear with negative numbers. For example, any assumed ordering would be broken; `127.0.0.0 < 128.0.0.0` would evaluate as false using `Int32` representations. – Douglas Dec 22 '12 at 10:10
2

You can parse the string to an IPAddress instance and then access the Address Property:

long result = IPAddress.Parse("174.36.207.186").Address;

Note that this will yield a compiler warning (obsolete property), because it doesn't work with IPv6.

dtb
  • 213,145
  • 36
  • 401
  • 431