views:

510

answers:

4

I was looking at the System.Net Namespace and it has an IPAddress instance you can use. This has a Parse method which you can use to parse a string into an IPInstance then use the Address property to give you the long value.

However...

The number returned is NOT the true conversion.

e.g. For IP 58.0.0.0 , the System.Net namespace gives me a value of 58... When in fact, the integer value should be 973078528

Can someone please show me the correct code do convert this?

The formula should be.. (for ip 192.1.20.10).

192 * (256*256*256) + 1 * (256*256) + 20 * (256) + 10

The reason this formula is correct is that the number it returns you can use in a >= and <= query to determine an IP address that falls within a range.

The Address Property (of the IPAddress instance) does not calculate/return this. A bonus point for anyone that knows why the address property does not return what I think is the correct answer...

Other examples from other links did not work either.

+3  A: 

Please see http://stackoverflow.com/questions/461742/how-to-convert-an-ip-address-into-an-integer-in-c

Andrew Hare
That question asked for a C# solution. This question is for .NET
lkessler
I don't understand what you mean "BitConverter.ToInt32(System.Net.IPAddress.Parse( address).GetAddressBytes(), 0);" *is* a .NET solution.
Andrew Hare
This question and accepted answer is not correct for my question.
Coolcoder
A: 

http://stackoverflow.com/questions/461742/how-to-convert-an-ip-address-into-a-integer-in-c

example code is listed in the picked answer

e; f, b

Luke
Just a tick too late.
Jeffrey
+1  A: 

What you are seeing appears to be an endian problem.

As a generic function, if your IP address is A.B.C.D then the value you're after is:

A << 24 +    (= A * 16777216)
B << 16 +    (= B *    65536)
C <<  8 +    (= C *      256)
D

On little endian machines when the four-byte array ABCD is cast into an integer it comes out with A as the least significant byte instead of the most significant.

I don't write vb.net code, but it should be pretty trivial to knock out a function that'll do this.

You'll need to ensure that A - D are all in the 0 .. 255 range first, though!

Alnitak
A: 

This might work, will try it and see.

public double IPAddressToNumber(string IPaddress)
    {
        int i;
        string [] arrDec;
        double num = 0;
        if (IPaddress == "")
        {
            return 0;
        }
        else
        {
            arrDec = IPaddress.Split('.');
            for(i = arrDec.Length - 1; i >= 0 ; i = i -1)
                {
                    num += ((int.Parse(arrDec[i])%256) * Math.Pow(256 ,(3 - i )));
                }
            return num;
        }
    }
Coolcoder
This does produce 973078528
Coolcoder
You code should return a long or Int64 not a double
Nick Berardi
also, in the loop, just multiply the value from the previous iteration by 256, and *then* add the next octet. Saves all those calls to Math.pow!
Alnitak