VS 2010 [RESOLVED] Get all IPs and PC names in a LAN using TCPClient-VBForums
Results 1 to 10 of 10

Thread: [RESOLVED] Get all IPs and PC names in a LAN using TCPClient

  1. #1

    Thread Starter
    Member
    Join Date
    Sep 2016
    Posts
    32

    Resolved [RESOLVED] Get all IPs and PC names in a LAN using TCPClient

    Hi
    I have created a simple LAN (ivp4). How can I get a list of IP addresses and names of all computers in the LAN using TCP/IP sockecting.( DNS not used.)
    Something in the lines of
    Code:
    For each 
    Listbox1.items.add(computer name &"_"& IPAddress)
    Next
    This is not (a chat or file )e transfer program.
    I haven't the least clue on how to proceed.
    Thanks

  2. #2
    Angel of Code Niya's Avatar
    Join Date
    Nov 2011
    Posts
    5,580

    Re: Get all IPs and PC names in a LAN using TCPClient

    This might work for you. It uses the address resolution protocol as a means of locating other connected PCs. The sample code is for VB6 but it's nothing that can't be translated to VB.Net or any other language.
    Treeview with NodeAdded/NodesRemoved events | BlinkLabel control | Calculate Permutations | Object Enums | ComboBox with centered items | .Net Internals article(not mine) | Wizard Control | Understanding Multi-Threading | Simple file compression | Demon Arena


    C++ programmers will dismiss you as a cretinous simpleton for your inability to keep track of pointers chained 6 levels deep and Java programmers will pillory you for buying into the evils of Microsoft. Meanwhile C# programmers will get paid just a little bit more than you for writing exactly the same code and VB6 programmers will continue to whitter on about "footprints". - FunkyDexter

    There's just no reason to use garbage like InputBox. -jmcilhinney

  3. #3

    Thread Starter
    Member
    Join Date
    Sep 2016
    Posts
    32

    Re: Get all IPs and PC names in a LAN using TCPClient

    I got the following (modified) code from here. (a Chat program)
    But when I run it I get the following FatalEnginException Error:

    The runtime has encountered a fatal error. The address of the error was at 0x887918d4, on thread 0x6e4. The error code is 0xc0000005. This error may be a bug in the CLR or in the unsafe or non-verifiable portions of user code. Common sources of this bug include user marshaling errors for COM-interop or PInvoke, which may corrupt the stack.

    The error occurs at the line:
    Code:
    ServerInfo = CType(Marshal.PtrToStructure(New IntPtr(CurPtr), GetType(SERVER_INFO_101)), SERVER_INFO_101)
    and error has to do with the CurPtr integer variable.
    Code:
    Imports System.Runtime.InteropServices
    
    Public Class Form1
        Public Const SV_TYPE_ALL As Integer = &HFFFFFFFF
    
        Public Structure SERVER_INFO_101
            Public Platform_ID As Integer
            <MarshalAsAttribute(UnmanagedType.LPWStr)> Public Name As String
            Public Version_Major As Integer
            Public Version_Minor As Integer
            Public Type As Integer
            <MarshalAsAttribute(UnmanagedType.LPWStr)> Public Comment As String
        End Structure
    
        Public Declare Unicode Function NetServerEnum Lib "Netapi32.dll" ( _
            ByVal Servername As Integer, ByVal Level As Integer, ByRef Buffer As Integer, ByVal PrefMaxLen As Integer, _
            ByRef EntriesRead As Integer, ByRef TotalEntries As Integer, ByVal ServerType As Integer, _
            ByVal DomainName As String, ByRef ResumeHandle As Integer) As Integer
    
        Public Declare Function NetApiBufferFree Lib "Netapi32.dll" (ByVal lpBuffer As Integer) As Integer
    
        Public Shared Function GetNetworkComputers(Optional ByVal DomainName As String = Nothing) As List(Of String)
            Dim ServerInfo As SERVER_INFO_101
            Dim MaxLenPref As Integer = -1
            Dim level As Integer = 101
            Dim ResumeHandle As Integer = 0
            Dim ret, EntriesRead, TotalEntries, BufPtr, CurPtr As Integer
            Dim ReturnList As New List(Of String)
    
            Try
                ret = NetServerEnum(0, level, BufPtr, MaxLenPref, EntriesRead, TotalEntries, SV_TYPE_ALL, DomainName, ResumeHandle)
                If ret = 0 Then
                    CurPtr = BufPtr
                    For i As Integer = 0 To EntriesRead - 1
                        ServerInfo = CType(Marshal.PtrToStructure(New IntPtr(CurPtr), GetType(SERVER_INFO_101)), SERVER_INFO_101)
                        CurPtr = CurPtr + Len(ServerInfo)
                        ReturnList.Add(ServerInfo.Name)
                    Next
                End If
                NetApiBufferFree(BufPtr)
            Catch ex As Exception
            End Try
    
            Return ReturnList
        End Function
    
        Private Sub btnGet_Click(sender As Object, e As EventArgs) Handles btnGet.Click
            LstBox.DataSource = GetNetworkComputers()
        End Sub
        
    End Class
    Any ideas

  4. #4
    Angel of Code Niya's Avatar
    Join Date
    Nov 2011
    Posts
    5,580

    Re: Get all IPs and PC names in a LAN using TCPClient

    Here, I made some changes to the code:-
    vbnet Code:
    1. Imports System.Runtime.InteropServices
    2.  
    3. Public Class Form1
    4.     Public Const SV_TYPE_ALL As Integer = &HFFFFFFFF
    5.  
    6.     Public Structure SERVER_INFO_101
    7.         Public Platform_ID As Integer
    8.         <MarshalAsAttribute(UnmanagedType.LPWStr)> Public Name As String
    9.         Public Version_Major As Integer
    10.         Public Version_Minor As Integer
    11.         Public Type As Integer
    12.         <MarshalAsAttribute(UnmanagedType.LPWStr)> Public Comment As String
    13.     End Structure
    14.  
    15.     Public Declare Unicode Function NetServerEnum Lib "Netapi32.dll" ( _
    16.         ByVal Servername As Integer, ByVal Level As Integer, ByRef Buffer As IntPtr, ByVal PrefMaxLen As Integer, _
    17.         ByRef EntriesRead As Integer, ByRef TotalEntries As Integer, ByVal ServerType As Integer, _
    18.         ByVal DomainName As String, ByRef ResumeHandle As Integer) As Integer
    19.  
    20.     Public Declare Function NetApiBufferFree Lib "Netapi32.dll" (ByVal lpBuffer As IntPtr) As Integer
    21.  
    22.     Public Shared Function GetNetworkComputers(Optional ByVal DomainName As String = Nothing) As List(Of String)
    23.         Dim ServerInfo As SERVER_INFO_101
    24.         Dim MaxLenPref As Integer = -1
    25.         Dim level As Integer = 101
    26.         Dim ResumeHandle As Integer = 0
    27.         Dim ret, EntriesRead, TotalEntries As Integer
    28.         Dim BufPtr As IntPtr
    29.         Dim ReturnList As New List(Of String)
    30.  
    31.         Try
    32.             ret = NetServerEnum(0, level, BufPtr, MaxLenPref, EntriesRead, TotalEntries, SV_TYPE_ALL, DomainName, ResumeHandle)
    33.             If ret = 0 Then
    34.                 For i As Integer = 0 To EntriesRead - 1
    35.  
    36.                     ServerInfo = Marshal.PtrToStructure(IncrementPointer(BufPtr, i * Marshal.SizeOf(ServerInfo)), GetType(SERVER_INFO_101))
    37.                     ReturnList.Add(ServerInfo.Name)
    38.                 Next
    39.             End If
    40.             NetApiBufferFree(BufPtr)
    41.         Catch ex As Exception
    42.         End Try
    43.  
    44.         Return ReturnList
    45.     End Function
    46.  
    47.     Private Shared Function IncrementPointer(ByVal ptr As IntPtr, ByVal i As Integer) As IntPtr
    48.         If IntPtr.Size = 4 Then
    49.             Return New IntPtr(ptr.ToInt32 + i)
    50.         End If
    51.  
    52.         If IntPtr.Size = 8 Then
    53.             Return New IntPtr(ptr.ToInt64 + i)
    54.         End If
    55.     End Function
    56.  
    57.     Private Sub btnGet_Click(sender As Object, e As EventArgs) Handles btnGet.Click
    58.         LstBox.DataSource = GetNetworkComputers()
    59.     End Sub
    60.  
    61.    
    62. End Class

    See if it works now.
    Treeview with NodeAdded/NodesRemoved events | BlinkLabel control | Calculate Permutations | Object Enums | ComboBox with centered items | .Net Internals article(not mine) | Wizard Control | Understanding Multi-Threading | Simple file compression | Demon Arena


    C++ programmers will dismiss you as a cretinous simpleton for your inability to keep track of pointers chained 6 levels deep and Java programmers will pillory you for buying into the evils of Microsoft. Meanwhile C# programmers will get paid just a little bit more than you for writing exactly the same code and VB6 programmers will continue to whitter on about "footprints". - FunkyDexter

    There's just no reason to use garbage like InputBox. -jmcilhinney

  5. #5

    Thread Starter
    Member
    Join Date
    Sep 2016
    Posts
    32

    Re: Get all IPs and PC names in a LAN using TCPClient

    Yes thanks Niya. the IncrementPointer function has solved the problem.
    Only the PC Names are listed. How about IP
    Code:
    For each 
    Listbox1.items.add(PC Name &"_"& IPAddress)
    Next

  6. #6
    Angel of Code Niya's Avatar
    Join Date
    Nov 2011
    Posts
    5,580

    Re: Get all IPs and PC names in a LAN using TCPClient

    Quote Originally Posted by gbhsk View Post
    Yes thanks Niya. the IncrementPointer function has solved the problem.
    Did you copy ONLY the IncrementPointer function to your code? I made more changes than that to the code you posted. Mainly, the original code wasn't using pointers correctly so I fixed all instances of incorrect use. You were meant to replace all of your original code with all the code I posted.

    Quote Originally Posted by gbhsk View Post
    Only the PC Names are listed. How about IP
    Code:
    For each 
    Listbox1.items.add(PC Name &"_"& IPAddress)
    Next
    You can use the a PC's name to obtain it's IP address:-
    vbnet Code:
    1. '
    2.         'The name of the PC goes in this variable
    3.         Dim pcName As String = "PCName"
    4.  
    5.         'Lists all the IP addresses assigned to the PC
    6.         'Note: This lists ALL addresses, even IPv6 addresses
    7.         For Each ip As Net.IPAddress In Net.Dns.GetHostAddresses(pcName)
    8.             Debug.WriteLine(ip.ToString)
    9.         Next

    The above code lists all the IP addresses assigned to a PC. As implied, you should be aware that a PC can have more than one IP address and many times will also have IPv6 addresses. So if you're only interested in one of these addresses, you will have to filter it out with. Also know that an exception would be thrown if the you give GetHostAddresses a host it can't find or one that doesn't exist.
    Last edited by Niya; Dec 15th, 2017 at 09:32 AM.
    Treeview with NodeAdded/NodesRemoved events | BlinkLabel control | Calculate Permutations | Object Enums | ComboBox with centered items | .Net Internals article(not mine) | Wizard Control | Understanding Multi-Threading | Simple file compression | Demon Arena


    C++ programmers will dismiss you as a cretinous simpleton for your inability to keep track of pointers chained 6 levels deep and Java programmers will pillory you for buying into the evils of Microsoft. Meanwhile C# programmers will get paid just a little bit more than you for writing exactly the same code and VB6 programmers will continue to whitter on about "footprints". - FunkyDexter

    There's just no reason to use garbage like InputBox. -jmcilhinney

  7. #7

    Thread Starter
    Member
    Join Date
    Sep 2016
    Posts
    32

    Re: Get all IPs and PC names in a LAN using TCPClient

    Yes I did use all the code which worked perfectly well providing PC names. Besides PC Names I also need static IPv4 IP addresses for the active PCs in the LAN. So the code snippet above may still have to be filtered further(with if statements perhaps) for any IPv4 addresses.
    Thanks

  8. #8
    Angel of Code Niya's Avatar
    Join Date
    Nov 2011
    Posts
    5,580

    Re: Get all IPs and PC names in a LAN using TCPClient

    Quote Originally Posted by gbhsk View Post
    Besides PC Names I also need static IPv4 IP addresses for the active PCs in the LAN.
    You will have to filter out the the IPv4 addresses yourself like this:-
    vbnet Code:
    1. '
    2.         'The name of the PC goes in this variable
    3.         Dim pcName As String = "PCName"
    4.  
    5.         'Lists all the IP addresses assigned to the PC
    6.         'Note: The lists ALL addresses, even IPv6 addresses
    7.         For Each ip As Net.IPAddress In Net.Dns.GetHostAddresses(pcName)
    8.  
    9.             'Only print out IPv4 Addresses
    10.             If ip.AddressFamily = Net.Sockets.AddressFamily.InterNetwork Then
    11.                 Debug.WriteLine(ip.ToString)
    12.             End If
    13.  
    14.         Next

    The above is a slight modification that prints only the IPv4 addresses. Be careful though. In practice you will get a single address for a PC most times but never assume that will always be the case. A networked device can have multiple network interfaces, such devices do include Windows PCs. If there are multiple IPv4 addresses for a host referenced by GetHostAddresses, they will be returned in the array. So always be prepared to handle such cases.
    Last edited by Niya; Dec 15th, 2017 at 01:04 PM.
    Treeview with NodeAdded/NodesRemoved events | BlinkLabel control | Calculate Permutations | Object Enums | ComboBox with centered items | .Net Internals article(not mine) | Wizard Control | Understanding Multi-Threading | Simple file compression | Demon Arena


    C++ programmers will dismiss you as a cretinous simpleton for your inability to keep track of pointers chained 6 levels deep and Java programmers will pillory you for buying into the evils of Microsoft. Meanwhile C# programmers will get paid just a little bit more than you for writing exactly the same code and VB6 programmers will continue to whitter on about "footprints". - FunkyDexter

    There's just no reason to use garbage like InputBox. -jmcilhinney

  9. #9

    Thread Starter
    Member
    Join Date
    Sep 2016
    Posts
    32

    Re: Get all IPs and PC names in a LAN using TCPClient

    And finally your previous snippet (modified) has made it.
    Thanks immensely.

    Final working code is below.
    Code:
    Imports System.Runtime.InteropServices
    
    Public Class Form1
        Public Const SV_TYPE_ALL As Integer = &HFFFFFFFF
    
        Public Structure SERVER_INFO_101
            Public Platform_ID As Integer
            <MarshalAsAttribute(UnmanagedType.LPWStr)> Public Name As String
            Public Version_Major As Integer
            Public Version_Minor As Integer
            Public Type As Integer
            <MarshalAsAttribute(UnmanagedType.LPWStr)> Public Comment As String
        End Structure
    
        Public Declare Unicode Function NetServerEnum Lib "Netapi32.dll" ( _
            ByVal Servername As Integer, ByVal Level As Integer, ByRef Buffer As IntPtr, ByVal PrefMaxLen As Integer, _
            ByRef EntriesRead As Integer, ByRef TotalEntries As Integer, ByVal ServerType As Integer, _
            ByVal DomainName As String, ByRef ResumeHandle As Integer) As Integer
    
        Public Declare Function NetApiBufferFree Lib "Netapi32.dll" (ByVal lpBuffer As IntPtr) As Integer
    
        Public Shared Function GetNetworkComputers(Optional ByVal DomainName As String = Nothing) As DataTable
            Dim ServerInfo As SERVER_INFO_101
            Dim MaxLenPref As Integer = -1
            Dim level As Integer = 101
            Dim ResumeHandle As Integer = 0
            Dim ret, EntriesRead, TotalEntries As Integer
            Dim BufPtr As IntPtr
    
            Dim dt As New DataTable
            dt.Columns.Add("IPs")
            dt.Columns.Add("PCs")
            Try
                ret = NetServerEnum(0, level, BufPtr, MaxLenPref, EntriesRead, TotalEntries, SV_TYPE_ALL, DomainName, ResumeHandle)
                If ret = 0 Then
                    For i As Integer = 0 To EntriesRead - 1
                        ServerInfo = Marshal.PtrToStructure(IncrementPointer(BufPtr, i * Marshal.SizeOf(ServerInfo)), GetType(SERVER_INFO_101))
                        Dim Rw As DataRow = dt.NewRow
    
                        Dim IPstring As String = ""
                        For Each ip As Net.IPAddress In Net.Dns.GetHostAddresses(ServerInfo.Name)
                            'Debug.WriteLine(ip.ToString)
                            If Not ip.IsIPv6LinkLocal Then
                                IPstring = IPstring & ip.ToString
                            End If
                        Next
                        Rw(0) = IPstring.ToString
                        Rw(1) = ServerInfo.Name.ToString
                        dt.Rows.Add(Rw)
                    Next
                End If
                NetApiBufferFree(BufPtr)
            Catch ex As Exception
                MsgBox(ex.Message)
            End Try
            Return dt
        End Function
    
        Private Shared Function IncrementPointer(ByVal ptr As IntPtr, ByVal i As Integer) As IntPtr
            If IntPtr.Size = 4 Then
                Return New IntPtr(ptr.ToInt32 + i)
            End If
            If IntPtr.Size = 8 Then
                Return New IntPtr(ptr.ToInt64 + i)
            End If
        End Function
    
        Private Sub btnGet_Click(sender As Object, e As EventArgs) Handles btnGet.Click
            'LstBx.DataSource = GetNetworkComputers()
            LstBx.Items.Clear()
            Dim dtt As DataTable = GetNetworkComputers()
            If dtt.Rows.Count > 0 Then
                For i As Integer = 0 To dtt.Rows.Count - 1
                    LstBx.Items.Add(dtt.Rows(i)(0).ToString & ":" & dtt.Rows(i)(1).ToString)
                Next
            End If
            dtt.Dispose()
        End Sub
    
    End Class

  10. #10
    Angel of Code Niya's Avatar
    Join Date
    Nov 2011
    Posts
    5,580

    Re: Get all IPs and PC names in a LAN using TCPClient

    Quote Originally Posted by gbhsk View Post
    Thanks immensely.
    You're welcomed.
    Treeview with NodeAdded/NodesRemoved events | BlinkLabel control | Calculate Permutations | Object Enums | ComboBox with centered items | .Net Internals article(not mine) | Wizard Control | Understanding Multi-Threading | Simple file compression | Demon Arena


    C++ programmers will dismiss you as a cretinous simpleton for your inability to keep track of pointers chained 6 levels deep and Java programmers will pillory you for buying into the evils of Microsoft. Meanwhile C# programmers will get paid just a little bit more than you for writing exactly the same code and VB6 programmers will continue to whitter on about "footprints". - FunkyDexter

    There's just no reason to use garbage like InputBox. -jmcilhinney

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Featured


Click Here to Expand Forum to Full Width

Survey posted by VBForums.