How to convert ipaddress to an integer

How can I convert an ip address to an integer for more efficient storage and back to an ip address.
kevinr188.Net DeveloperAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.


Public Type myBytes
    B1 As Byte
    B2 As Byte
    B3 As Byte
    B4 As Byte
End Type

Public Type myLong
    Val As Long
End Type

Public Function IP2Long(IP As String) As Long
    ReDim parse(0 To 3) As String
    Dim B As myBytes
    Dim L As myLong
    parse = Split(IP, ".")
    B.B1 = Val(parse(0))
    B.B2 = Val(parse(1))
    B.B3 = Val(parse(2))
    B.B4 = Val(parse(3))
    LSet L = B
    IP2Long = L.Val
End Function

Public Function Long2IP(ByVal IP As Long) As String
    Dim L As myLong
    Dim B As myBytes
    L.Val = IP
    LSet B = L
    Long2IP = Trim(Str$(B.B1)) + "." + Trim(Str$(B.B2)) + "." + Trim(Str$(B.B3)) + "." + Trim(Str$(B.B4))
End Function
Andrew CroftsCommented:
             Public Function IPAddressToNumber(ByVal  IPaddress As String) As  Double
    Dim i As  Integer
    Dim arrDec As  String()
    Dim num As  Double = 0
    If IPaddress = "" Then
        Return 0
        arrDec = IPaddress.Split("."c)
        For i = arrDec.Length - 1 To 0 Step -1
            num += ((Integer.Parse(arrDec(i)) Mod  256) * Math.Pow(256, (3 - i)))
        Return num
    End If
End Function

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
How to use .Net framework classes properly:
// C#
long ipLong = IPAddress.Parse("").Address;
string ipString = new IPAddress(ipLong).ToString();

Dim ipLong As Long = IPAddress.Parse("").Address
Dim ipString As String = New IPAddress(ipLong).ToString()

Open in new window

It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
.NET Programming

From novice to tech pro — start learning today.