kevinr188
asked on
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.
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
How to use .Net framework classes properly:
// C#
long ipLong = IPAddress.Parse("192.165.1.1").Address;
string ipString = new IPAddress(ipLong).ToString();
'VB
Dim ipLong As Long = IPAddress.Parse("192.165.1.1").Address
Dim ipString As String = New IPAddress(ipLong).ToString()
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
Code:
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