日期:2010-08-02  浏览次数:20968 次

将IP地址转换为长整型

Converts a string ip address ("192.168.0.1") to a Long number (3232235521). One of the reasons to do this would be to store IP addresses in databases. Numbers greatly reduce the size required to store this information.
Inputs: asNewIP - String IP address ("192.168.0.1") to convert to a number.

Returns: Returns a Long Integer representing the IP address (3232235521)

Assumes: This function assumes that your IP address has 4 integers delimited by decimals and that the numbers range from 0 to 255.

Function CLngIP(ByVal asNewIP)
Dim lnResults
Dim lnIndex
Dim lnIpAry
' Split the IP address using the dot as a delimiter
lnIpAry = Split(asNewIP, ".", 4)
' Loop through Each number In the IP address
For lnIndex = 0 To 3

' If we are Not working With the last number...
If Not lnIndex = 3 Then

' Convert the number To a value range that can be parsed from the others
lnIpAry(lnIndex) = lnIpAry(lnIndex) * (256 ^ (3 - lnIndex))

End If

' Add the number To the results
lnResults = lnResults + lnIpAry(lnIndex)

Next
' If storing number within an Access Database,
' The variable Type "Long" ranges from -2147483648 To 2147483647
' You will need To subtract 2147483648 from the number
' before querying the database.

' lnResults = lnResults - 2147483648
' Return the results
CLngIP = lnResults
End Function

将长整型转换为IP地址

Name: Convert LongIP to StringIP
Description: This function converts a Long Number (3232235521) into an IP Address ("192.168.0.1"). Why would you want to do this? Click here.
Inputs: anNewIP - IP Address as a Long Number (no dots)

Returns: Returns the string representation of an IP Address ("192.168.0.1")

Function CStrIP(ByVal anNewIP)
Dim lsResults ' Results To be returned
Dim lnTemp ' Temporary value being parsed
Dim lnIndex ' Position of number being parsed
' If pulling number from an Access Database,
' The variable Type "Long" ranges from -2147483648 To 2147483647
' You will first need To add 2147483648 to the number to parse correctly.
' anNewIP = anNewIP + 2147483648
' Parse highest numbers first
For lnIndex = 3 To 0 Step -1

' Parse the current value For this position
lnTemp = Int(anNewIP / (256 ^ lnIndex))

' Append the number To the final results delimited by a dot
lsResults = lsResults & lnTemp & "."

' Remove the number that we just parsed
anNewIP = anNewIP - (lnTemp * (256 ^ lnIndex))

Next

' Cut off last dot
lsResults = Left(lsResults, Len(lsResults) - 1)

' Return the results
CStrIP = lsResults

End Function