Convert an IP Address to an Integer
This is a pretty basic function which allows you to convert an IP address, which a string, into a long integer. But where would this be useful?
A Basic Example
Let's say you have a website, and you want to disallow certain IP address ranges from accessing the site. Let pretend that you want to stop the range of 101.128.0.0 - 101.128.3.255. You have to have a way to check if the user IP is in that range.
Using string based variables to perform this comparison is madness. You'll drive yourself bonkers trying to do this. Instead, you convert the above into integers, and store that in your database. The lower number will be the start of the range, and the higher number will be end of the range. Using the example range above, the converted values are 1702887424 for the lower end, and 1702888447 for the upper end.
Now, when a visitor comes to the site, grab the IP address, convert it to an integer, see if it falls within a blocked range. You can do this with a simple MySQL (or MS SQL) query:
strSQL="select Count(*) As NumResults from tblIPBlockList where dblStart<=1702887424 AND dblEnd>=1702888447"
If you get more than 0 results back from the query, then you'll know that the visitors IP address falls within that range.
The Code
The function is listed below, and is pretty straightforward in its use. If you have any questions, hit me up.
Function CLngIP(ByVal asNewIP)
' 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
' haven't reached 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
CLngIP = lnResults
End Function
Special Instructions
If you try using this with an Access database, note that the long integer field type won't hold these values. Instead, you might use the currency field type to get around this.
Loading Comments ...
Comments
No comments have been added for this post.
You must be logged in to make a comment.