jewbacca jewbacca - 14 days ago 6
Vb.net Question

Read IP Address using SQLDataReader

Working with an ASP.Net application where I would like to pull IPv4 information from a SQL database using SQLDataReader. When reading an IP from SQL the data type is binary and I am not sure the best way to handle this.

Since there is no method for SQLDataReader.GetIPAddress() it seems that I would need to use SQLDataReader.GetBytes()? Many examples online around how to do this however since getstring is very simple I am hoping there is another simpler way to use getbyte() or another method to bring in the IP.

Do While SQLReader.Read()
Dim lastcom As System.DateTime = SQLReader.GetDateTime(0)
Debug.WriteLine(lastcom.ToString("MM/dd/yyyy HH:mm:ss.fff"))
Debug.WriteLine(SQLReader.GetString(1))
Debug.WriteLine(SQLReader.GetBoolean(2))
Debug.WriteLine(SQLReader.GetString(3))
Debug.WriteLine(SQLReader.GetString(4))
Label_IP = SQLReader.GetString(1)
Label_Model.Text = SQLReader.GetString(4)
Loop

Answer

I am making some assumptions about how the IP address is stored in the database (and only supporting IPv4 addresses), but you could try something like this:

Dim ipAddr(3) As Byte
' Assuming that column #1 is your IP address column
Dim byteCount = SQLReader.GetBytes(1, 0, ipAddr, 0, 4)
If byteCount = 4 Then
    Label_IP.Text = New IPAddress(ipAddr).ToString()
Else
    Console.WriteLine("Expected 4 bytes for IP address")
End If
Comments