VB.NET代码从网络获取所有机器名称及其IP [英] VB.NET code to get all machine names with their IP from network
本文介绍了VB.NET代码从网络获取所有机器名称及其IP的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
需要获取一个代码来显示所有连接到网络的电脑,以及哪些电脑将显示在列表中以供进一步操作选择。
解决方案
这是未经验证的 - 它是我的C#方法自动转换为VB。它基于我的提示:检索IP和MAC地址局域网 [ ^ ]
''' < 摘要 >
''' GetIpNetTable外部方法
''' < / summary >
''' < param name =pIpNetTable > < / param >
''' < span class =code-summarycomment>< param name =pdwSize > < / param >
''' < param name =bOrder > < / param >
''' < 返回 > < / returns < span class =code-summarycomment>>
< DllImport( IPHLPAPI.DLL跨度>)GT; _
私有 共享 功能 GetIpNetTable(pIpNetTable As IntPtr ,< MarshalAs(UnmanagedType.U4)> ByRef pdwSize 作为 整数,bOrder As Boolean ) As < MarshalAs(UnmanagedType.U4)> 整数
结束 功能
''' < 摘要 >
' '' 错误代码GetIpNetTable返回我们识别
''' < / summary >
Const ERROR_INSUFFICIENT_BUFFER As 整数 = 122
''' < 摘要 >
''' GetIpNetTable返回的MIB_IPNETROW结构
'' ' 不要修改这种结构。
''' < / summary >
< StructLayout(LayoutKind.Sequential)> ; _
私有 结构 MIB_IPNETROW
< MarshalAs(UnmanagedType.U4)> _
公共 dwIndex 作为 整数
< MarshalAs(UnmanagedType.U4)> _
公开 dwPhysAddrLen 作为 整数
< MarshalAs(UnmanagedType.U1)> _
公开 mac0 作为 字节
< MarshalAs(UnmanagedType.U1)> _
公开 mac1 作为 字节
< MarshalAs(UnmanagedType.U1)> _
公开 mac2 作为 字节
< MarshalAs(UnmanagedType.U1)> _
公开 mac3 作为 字节
< MarshalAs(UnmanagedType.U1)> _
公开 mac4 作为 字节
< MarshalAs(UnmanagedType.U1)> _
公开 mac5 作为 字节
< MarshalAs(UnmanagedType.U1)> _
公开 mac6 作为 字节
< MarshalAs(UnmanagedType.U1)> _
公开 mac7 作为 字节
< MarshalAs(UnmanagedType.U4)> _
公开 dwAddr 作为 整数
< MarshalAs(UnmanagedType.U4)> _
公共 dwType 作为 整数
结束 结构
''' < summary >
''' 获取局域网上所有已知设备的IP和MAC地址
''' < / summary >
''' < < span class =code-summarycomment>备注 >
''' 1 )此表不经常更新 - 可能需要一些人工时间
''' 注意到设备已从网络中删除,或新设备
''' 已连接。
''' 2)如果找到非本地设备,则会丢弃这些设备 - 这些是multicast
''' ,可以按IP地址范围丢弃。
''' < /备注 >
''' < 返回 < span class =code-summarycomment>> < / returns >
公开 共享 函数 GetAllDevicesOnLAN()作为字典( of IPAddress,PhysicalAddress)
Dim all As 新字典( IPAddress,PhysicalAddress)()
' 添加此项PC到列表...
all.Add(GetIPAddress(),GetMacAddress())
Dim spaceForNetTable 作为 整数 = 0
' 获取所需空间
' < span class =code-comment>我们通过请求表来做到这一点,但根本没有提供任何空间。
' 返回值将告诉我们实际需要多少。
GetIpNetTable( IntPtr .Zero,spaceForNetTable, 错误)
' 分配水疗中心ce
' 我们使用try-finally块来确保发布。
Dim rawTable As IntPtr = IntPtr .Zero
尝试
rawTable = Marshal.AllocCoTaskMem(spaceForNetTable)
' 获取实际数据
Dim errorCode 作为 整数 = GetIpNetTable(rawTable,spaceForNetTable,错误)
如果 errorCode<> 0 然后
' < span class =code-comment>由于某种原因失败 - 在这里不能再做了。
投掷 新异常(字符串 .Format( 无法检索网络表。错误代码{0},errorCode))
结束 如果
' 获取行数
Dim rowsCount As 整数 = Marshal.ReadInt32(rawTable) )
Dim currentBuffer 作为 新 IntPtr (rawTable.ToInt64()+ Marshal.SizeOf( GetType ( Int32 )))
' 将原始表转换为单独的条目
Dim 行作为 MIB_IPNETROW()= 新 MIB_IPNETROW(rowsCount - 1 ){}
对于 index 作为 整数 = 0 至 rowsCount - 1
rows(index)= CType (Marshal.PtrToStructure( 新 IntPtr (currentBuffer.ToInt64()+(index * Marshal.SizeOf( GetType (MIB_IPNETROW)))), GetType (MIB_IPNETROW)),MIB_IPNETROW)
下一步
' 定义虚拟条目列表(我们可以丢弃这些)
Dim virtualMAC 作为 新 PhysicalAddress(新 字节(){ 0 , 0 , 0 , 0 ,< span class =code-digit> 0 , 0 })
Dim broadcastMAC 作为 新 PhysicalAddress(新 < span class =code-keyword> Byte (){ 255 , 255 , 255 , 255 , 255 , 255 })
对于 每个行作为 MIB_IPNETROW 在 rows
Dim ip As New IPAddress(BitConverter.GetBytes(row.dwAddr))
Dim rawMAC As 字节()= 新 字节() {row.mac0,row.mac1,row.mac2,row.mac3,row.mac4,row.mac5}
Dim pa As 新 PhysicalAddress(rawMAC)
如果 不 pa.Equals(virtualMAC) AndAlso 不 pa.Equals(broadcastMAC) AndAlso 不 IsMulticast(ip)然后
' Console.WriteLine(IP:{0} \t\tMAC:{1},ip.ToString(),pa.ToString());
如果 不 all.ContainsKey(ip)那么
all.Add(ip,pa)
结束 如果
结束 如果
下一步
Fi nally
' 释放内存。
Marshal.FreeCoTaskMem( rawTable)
结束 尝试
返回所有
结束 功能
尝试这个,它将通过LAN提供所有连接的机器名称....
进口系统.IO
Imports System.DirectoryServices
Public Class Form1
Private Sub Form1_Load(sender as System。 Object ,e As System.EventArgs)Handles MyBase.Load
FindingThreats()
End Sub
Sub FindingThreats()
ListView1.Items.Clear()
Dim childEntry As DirectoryEntry
Dim ParentEntry As New DirectoryEntry
试试
ParentEntry.Path = WinNT:
For ParentEntry.Children $ b $中的每个childEntry b选择案例childEntry.SchemaClassName
案例 域
Dim SubChildEntry As DirectoryEntry
Dim SubParentEntry As New DirectoryEntry
SubParentEntry.Path = WinNT:// & childEntry.Name
For SubCharentEntry.Children
选择Case SubChildEntry.SchemaClassName
Case 计算机
ListView1.Items.Add(SubChildEntry.Name)
结束选择
下一个
结束选择
下一个
Catch Excep As Exception
MsgBox( 读取目录时出错: + Excep .Message.ToString)
最后
ParentEntry =没什么
结束尝试
结束子
结束班
从工具箱中拖放列表视图,然后将属性设置为
1。查看 - 详细信息
2. FullRowSelect - true
3. GridLines - true
这就是所有
问候
Sarva
使用 Dns.GetHostEntry方法 [ ^ ]获取计算机(主机)名称的IP地址。
示例
Dim strHostName As String =www.codeproject.com
Dim strIPAddress As String =
Dim objAddressList()As System.Net.IPAddress = _
System.Net.Dns.GetHostEntry(strHostName).AddressList
For x = 0 to objAddressList.GetUpperBound(0)
if objAddressList (x).AddressFamily = Net.Sockets.AddressFamily.InterNetwork然后
strIPAddress = objAddressList(x).ToString
退出
结束如果
下一步
need to get a code to show all pc's connected to network and which will be shown in the list to select for further action .
解决方案
This is untried - it is an automatic conversion of my C# method to VB. It's based on my Tip here: Retrieving IP and MAC addresses for a LAN[^]
''' <summary> ''' GetIpNetTable external method ''' </summary> ''' <param name="pIpNetTable"></param> ''' <param name="pdwSize"></param> ''' <param name="bOrder"></param> ''' <returns></returns> <DllImport("IpHlpApi.dll")> _ Private Shared Function GetIpNetTable(pIpNetTable As IntPtr, <MarshalAs(UnmanagedType.U4)> ByRef pdwSize As Integer, bOrder As Boolean) As <MarshalAs(UnmanagedType.U4)> Integer End Function ''' <summary> ''' Error codes GetIpNetTable returns that we recognise ''' </summary> Const ERROR_INSUFFICIENT_BUFFER As Integer = 122 ''' <summary> ''' MIB_IPNETROW structure returned by GetIpNetTable ''' DO NOT MODIFY THIS STRUCTURE. ''' </summary> <StructLayout(LayoutKind.Sequential)> _ Private Structure MIB_IPNETROW <MarshalAs(UnmanagedType.U4)> _ Public dwIndex As Integer <MarshalAs(UnmanagedType.U4)> _ Public dwPhysAddrLen As Integer <MarshalAs(UnmanagedType.U1)> _ Public mac0 As Byte <MarshalAs(UnmanagedType.U1)> _ Public mac1 As Byte <MarshalAs(UnmanagedType.U1)> _ Public mac2 As Byte <MarshalAs(UnmanagedType.U1)> _ Public mac3 As Byte <MarshalAs(UnmanagedType.U1)> _ Public mac4 As Byte <MarshalAs(UnmanagedType.U1)> _ Public mac5 As Byte <MarshalAs(UnmanagedType.U1)> _ Public mac6 As Byte <MarshalAs(UnmanagedType.U1)> _ Public mac7 As Byte <MarshalAs(UnmanagedType.U4)> _ Public dwAddr As Integer <MarshalAs(UnmanagedType.U4)> _ Public dwType As Integer End Structure ''' <summary> ''' Get the IP and MAC addresses of all known devices on the LAN ''' </summary> ''' <remarks> ''' 1) This table is not updated often - it can take some human-scale time ''' to notice that a device has dropped off the network, or a new device ''' has connected. ''' 2) This discards non-local devices if they are found - these are multicast ''' and can be discarded by IP address range. ''' </remarks> ''' <returns></returns> Public Shared Function GetAllDevicesOnLAN() As Dictionary(Of IPAddress, PhysicalAddress) Dim all As New Dictionary(Of IPAddress, PhysicalAddress)() ' Add this PC to the list... all.Add(GetIPAddress(), GetMacAddress()) Dim spaceForNetTable As Integer = 0 ' Get the space needed ' We do that by requesting the table, but not giving any space at all. ' The return value will tell us how much we actually need. GetIpNetTable(IntPtr.Zero, spaceForNetTable, False) ' Allocate the space ' We use a try-finally block to ensure release. Dim rawTable As IntPtr = IntPtr.Zero Try rawTable = Marshal.AllocCoTaskMem(spaceForNetTable) ' Get the actual data Dim errorCode As Integer = GetIpNetTable(rawTable, spaceForNetTable, False) If errorCode <> 0 Then ' Failed for some reason - can do no more here. Throw New Exception(String.Format("Unable to retrieve network table. Error code {0}", errorCode)) End If ' Get the rows count Dim rowsCount As Integer = Marshal.ReadInt32(rawTable) Dim currentBuffer As New IntPtr(rawTable.ToInt64() + Marshal.SizeOf(GetType(Int32))) ' Convert the raw table to individual entries Dim rows As MIB_IPNETROW() = New MIB_IPNETROW(rowsCount - 1) {} For index As Integer = 0 To rowsCount - 1 rows(index) = CType(Marshal.PtrToStructure(New IntPtr(currentBuffer.ToInt64() + (index * Marshal.SizeOf(GetType(MIB_IPNETROW)))), GetType(MIB_IPNETROW)), MIB_IPNETROW) Next ' Define the dummy entries list (we can discard these) Dim virtualMAC As New PhysicalAddress(New Byte() {0, 0, 0, 0, 0, 0}) Dim broadcastMAC As New PhysicalAddress(New Byte() {255, 255, 255, 255, 255, 255}) For Each row As MIB_IPNETROW In rows Dim ip As New IPAddress(BitConverter.GetBytes(row.dwAddr)) Dim rawMAC As Byte() = New Byte() {row.mac0, row.mac1, row.mac2, row.mac3, row.mac4, row.mac5} Dim pa As New PhysicalAddress(rawMAC) If Not pa.Equals(virtualMAC) AndAlso Not pa.Equals(broadcastMAC) AndAlso Not IsMulticast(ip) Then 'Console.WriteLine("IP: {0}\t\tMAC: {1}", ip.ToString(), pa.ToString()); If Not all.ContainsKey(ip) Then all.Add(ip, pa) End If End If Next Finally ' Release the memory. Marshal.FreeCoTaskMem(rawTable) End Try Return all End Function
try this it will give all connected machine Name over the LAN....
Imports System.IO Imports System.DirectoryServices Public Class Form1 Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load FindingThreats() End Sub Sub FindingThreats() ListView1.Items.Clear() Dim childEntry As DirectoryEntry Dim ParentEntry As New DirectoryEntry Try ParentEntry.Path = "WinNT:" For Each childEntry In ParentEntry.Children Select Case childEntry.SchemaClassName Case "Domain" Dim SubChildEntry As DirectoryEntry Dim SubParentEntry As New DirectoryEntry SubParentEntry.Path = "WinNT://" & childEntry.Name For Each SubChildEntry In SubParentEntry.Children Select Case SubChildEntry.SchemaClassName Case "Computer" ListView1.Items.Add(SubChildEntry.Name) End Select Next End Select Next Catch Excep As Exception MsgBox("Error While Reading Directories : " + Excep.Message.ToString) Finally ParentEntry = Nothing End Try End Sub End Class
drag and drop a list view from toolbox then set properties to
1. View - Details
2. FullRowSelect - true
3. GridLines - true
thats all
Regards
Sarva
Use Dns.GetHostEntry Method[^] to get an IP Address for a computer (host) name.
Example
Dim strHostName As String = "www.codeproject.com" Dim strIPAddress As String = "" Dim objAddressList() As System.Net.IPAddress = _ System.Net.Dns.GetHostEntry(strHostName).AddressList For x = 0 To objAddressList.GetUpperBound(0) If objAddressList(x).AddressFamily = Net.Sockets.AddressFamily.InterNetwork Then strIPAddress = objAddressList(x).ToString Exit For End If Next
这篇关于VB.NET代码从网络获取所有机器名称及其IP的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文