Friday, February 24, 2012

Convert IP Address to Long

Hi, can I use a SQL server Stored Procedure to convert an IP Address to Long?

In VB.NET I use the following code (hope that helps).


Private Function ConvertToLong(ByVal IPAddress As Object) As Object

Dim x As Integer
Dim Pos As Integer
Dim PrevPos As Integer
Dim Num As Integer

If UBound(Split(IPAddress, ".")) = 3 Then
' On Error Resume Next
For x = 1 To 4
Pos = InStr(PrevPos + 1, IPAddress, ".", 1)
If x = 4 Then Pos = Len(IPAddress) + 1
Num = Int(Mid(IPAddress, PrevPos + 1, Pos - PrevPos - 1))
If Num > 255 Then
ConvertToLong = "0"
Exit Function
End If
PrevPos = Pos
ConvertToLong = ((Num Mod 256) * (256 ^ (4 - x))) + ConvertToLong
Next
End If

End Function

Here's a UDF that should do what you are looking for.

Usage: SELECT dbo.fnStringIPToLongIP('192.168.0.1')


CREATE FUNCTION dbo.fnStringIPToLongIP (@.IPAddress AS varchar(15))
RETURNS bigint AS
BEGIN

DECLARE
@.x Integer,
@.Pos Integer,
@.PrevPos Integer,
@.Num Integer,
@.ConvertToLong bigint

SET @.ConvertToLong = 0

IF LEN(RTRIM(REPLACE(@.IPAddress,'.',''))) = LEN(RTRIM(@.IPAddress))-3
BEGIN
SET @.X = 1
SET @.PrevPos = 0
WHILE @.X <= 4
BEGIN
SET @.Pos = CHARINDEX('.',@.IPAddress,@.PrevPos + 1)
IF @.x = 4
SET @.Pos = Len(@.IPAddress) + 1

SET @.Num = SUBSTRING(@.IPAddress, @.PrevPos + 1, @.Pos - @.PrevPos - 1)
If @.Num > 255
BEGIN
SET @.ConvertToLong = '0'
SET @.X = 5
BREAK
END
SET @.PrevPos = @.Pos
SET @.ConvertToLong = ((@.Num % 256) * CAST(POWER(256,(4 - @.x)) AS bigint)) + @.ConvertToLong
SET @.X = @.X + 1
END
END

RETURN(@.ConvertToLong)

END

Terri|||Thanks a million!!!|||FYI...The EasyWay.NET


Dim lng As Long = System.Net.IPAddress.Parse("192.168.0.1").Address

No comments:

Post a Comment