vb.net网络编程-列出网络接口

时间:2018-08-22 01:52:53

标签: vb.net network-programming

我对VB.net有点陌生,并尝试提取所有网络接口状态并将其显示在列表框中。

我能够提取网络接口卡名称和MAC地址,并将它们列出在前两列中。

但是,在提取其他数据时,我遇到了一个例外:

  

索引超出范围。必须为非负数且小于   集合。参数名称:索引

有人可以向我解释这里到底发生了什么,并指出正确的方向吗?

我有以下代码:

Imports System.Net.NetworkInformation

Public Class networkInterfaces
Private Sub showNetInts_Click(sender As Object, e As EventArgs) Handles showNetInts.Click
    getInterfaces()
End Sub

Private Sub getinterfaces()
    Dim nics As NetworkInterface() = NetworkInterface.GetAllNetworkInterfaces()

    If nics.Length < 0 Or nics Is Nothing Then
        MsgBox("No network interfaces found.")
    End If

    netInterfaces.Items.Clear()

    For Each netadapter As NetworkInterface In nics
        'get interface properties
        Dim intProperties As IPInterfaceProperties = netadapter.GetIPProperties

        netInterfaces.Items.Add(netadapter.Name)

        Dim physAddr As PhysicalAddress = netadapter.GetPhysicalAddress
        Dim addbyte As Byte() = physAddr.GetAddressBytes

        Dim macAddr As String = ""
        'loop through bytes value and change value to hex
        For i = 0 To addbyte.Length - 1
            macAddr &= addbyte(i).ToString("X2") 'changes string to hex
            'separate hex value with "-", except last value
            If i <> addbyte.Length - 1 Then
                macAddr &= "-"
            End If
        Next

        Dim icount As Integer = netInterfaces.Items.Count

            With netInterfaces.Items(icount - 1).SubItems
            .Add(macAddr)
            .Add(intProperties.UnicastAddresses(1).Address.ToString) ' 2 index = ipv4 addr
            .Add(intProperties.UnicastAddresses(1).IPv4Mask.ToString) ' gets mask addr
            .Add(intProperties.UnicastAddresses(0).Address.ToString) ' 0 index - ipv6 addr

    Next

1 个答案:

答案 0 :(得分:1)

这是我的意思的例子:

  

如果是这样,那么您只需要两个嵌套的If块,外层一个   检查Count是否大于0以及内部是否大于1   检查它是否大于1。

If intProperties.UnicastAddresses.Count > 0 Then
    If intProperties.UnicastAddresses.Count > 1 Then
        .Add(intProperties.UnicastAddresses(1).Address.ToString) ' 2 index = ipv4 addr
        .Add(intProperties.UnicastAddresses(1).IPv4Mask.ToString) ' gets mask addr
    End If

    .Add(intProperties.UnicastAddresses(0).Address.ToString) ' 0 index - ipv6 addr
End If