Krishanu Dey
Krishanu Dey

Reputation: 6406

List the IP Address of all computers connected to LAN in vb6

I want to list all the IP Address connected LAN into a listbox in VB6. Ive visited this. But I want to do this in VB6. I've no idea about how to do this. Any help is appreciated.

Upvotes: 1

Views: 9308

Answers (1)

Mark Bertenshaw
Mark Bertenshaw

Reputation: 5689

Using a WinSock control (wsck) purely for being a way to get the local IP address, use this code:

Option Explicit

Private Type IPAddr
    s_b1    As Byte
    s_b2    As Byte
    s_b3    As Byte
    s_b4    As Byte
End Type

Private Type IPAddrCompat
    ul      As Long
End Type

Private Type MacAddress
    s_b1    As Byte
    s_b2    As Byte
    s_b3    As Byte
    s_b4    As Byte
    s_b5    As Byte
    s_b6    As Byte
    unused  As Integer
End Type

Private Declare Function SendARP Lib "Iphlpapi.dll" ( _
    ByVal DestIP As Long, _
    ByVal SrcIP As Long, _
    ByRef pMacAddr As MacAddress, _
    ByRef PhyAddrLen As Long _
) As Long

Private Sub cmdGetIPs_Click()

    Dim nIndex As Long

    Dim vasLocalIP          As Variant
    Dim uIPAddr             As IPAddr
    Dim uIPAddrCompat       As IPAddrCompat
    Dim uMacAddr            As MacAddress
    Dim nMacAddrLen         As Long

    vasLocalIP = Split(wsck.LocalIP, ".")
    uIPAddr.s_b1 = CByte(vasLocalIP(0))
    uIPAddr.s_b2 = CByte(vasLocalIP(1))
    uIPAddr.s_b3 = CByte(vasLocalIP(2))

    ' Iterate through all valid addresses in the final quartet.
    For nIndex = 1 To 254
        uIPAddr.s_b4 = CByte(nIndex)
        LSet uIPAddrCompat = uIPAddr ' Convert 4 bytes into 1 long.
        nMacAddrLen = 8 ' Indicate that we are allocating a buffer with 8 bytes.

        ' Try to find the MAC address for this IP.
        If SendARP(uIPAddrCompat.ul, 0&, uMacAddr, nMacAddrLen) = 0 Then
            ' MAC addresses are 6 bytes long.
            If nMacAddrLen = 6 Then
                vasLocalIP(3) = CStr(nIndex)
                Debug.Print Join(vasLocalIP, "."), MacAddrString(uMacAddr, nMacAddrLen)
            End If
        End If
    Next nIndex

End Sub

' Returns the MAC address as a six byte hex string.
Private Function MacAddrString(ByRef the_uMacAddr As MacAddress, ByVal the_nMacAddrLen) As String

    With the_uMacAddr
        MacAddrString = Hex2(.s_b1) & ":" & Hex2(.s_b2) & ":" & Hex2(.s_b3) & ":" & Hex2(.s_b4) & ":" & Hex2(.s_b5) & ":" & Hex2(.s_b6)
    End With

End Function

' Returns the byte as a two digit hex string.
Private Function Hex2(ByVal the_byt As Byte) As String

    Hex2 = Hex$(the_byt)
    If Len(Hex2) = 1 Then
        Hex2 = "0" & Hex2
    End If

End Function

Upvotes: 2

Related Questions