vb.net 第二十一节 增加和删除一个IP地址

Posted VB.Net

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了vb.net 第二十一节 增加和删除一个IP地址相关的知识,希望对你有一定的参考价值。

版权声明:本文为博主原创文章,转载请在显著位置标明本文出处以及作者网名,未经作者允许不得用于商业目的。

Imports System.Runtime.InteropServices

Public Class Form22
    Const MAX_ADAPTER_NAME_LENGTH = 256
    Const MAX_ADAPTER_ADDRESS_LENGTH = 8
    Const MAX_ADAPTER_DESCRIPTION_LENGTH = 128

    <StructLayout(LayoutKind.Sequential)>
    Public Structure MIB_IPADDRROW
        Public dwAddr As Integer       '接口的IP地址
        Public dwIndex As Integer      '与IP地址关联的接口之索引
        Public dwMask As Integer   '子网掩码
        Public dwBCastAddr As Integer  '广播地址
        Public dwReasmSize As Integer  '已收到的数据报重装后的最大长度
        Public unused1 As Short       '未使用
        Public unused2 As Short       '未使用
    End Structure

    <StructLayout(LayoutKind.Sequential)>
    Public Structure MIB_IPADDRTABLE
        Public dwNumEntries As Integer         '表明table字段数组中有多少MIB_IPADDROW条目
        Public table() As MIB_IPADDRROW '指向MIB_IPADDRROW类型
    End Structure

    <StructLayout(LayoutKind.Sequential)>
    Public Structure IP_ADDR_STRING
        Public [Next] As IntPtr     '指向列表中下一个IP_ADDR_STRING类型。为空,则是最后一个地址
        <MarshalAs(UnmanagedType.ByValArray, SizeConst:=16)> Public IpAddress() As Char     '点式十进制字串表示Ip地址
        <MarshalAs(UnmanagedType.ByValArray, SizeConst:=16)> Public IpMask() As Char       '子网掩码
        Public Context As Integer      '网络IP地址标识,符合AddIPAddress和DeleteIPAddress函数中的网络接口关联参数。
    End Structure

    <StructLayout(LayoutKind.Sequential)>
    Public Structure IP_ADAPTER_INFO
        Public [Next] As IntPtr           '在适配器列表中指向下一个适配器
        Public ComboIndex As Integer '保留未用
        <MarshalAs(UnmanagedType.ByValArray, SizeConst:=MAX_ADAPTER_NAME_LENGTH + 4)> Public AdapterName() As Char          '适配器名
        <MarshalAs(UnmanagedType.ByValArray, SizeConst:=MAX_ADAPTER_DESCRIPTION_LENGTH + 4)> Public Description() As Char      '    '对网卡的描述,实际上好象是驱动程序的名字
        Public AddressLength As Integer        '适配器物理地址的长度 
        <MarshalAs(UnmanagedType.ByValArray, SizeConst:=MAX_ADAPTER_ADDRESS_LENGTH)> Public Address() As Byte          '物理地址,每个字节存放一个十六进制的数值
        Public Index As Integer            '适配器索引号
        Public Type As Integer         '适配器类型,包含以下类型的适配器(见下表):
        Public DhcpEnabled As Integer        '适配器是否启用了动态主机配置协议(DHCP)
        '在vb6版本中使用的是Long,其实这里是个指针,在vb6下面没错,但是在64位系统下就有问题
        Public CurrentIpAddress As IntPtr  '保留(当前使用的IP地址?)
        Public IpAddressList As IP_ADDR_STRING      '绑定到此适配器的IP地址链表
        Public GatewayList As IP_ADDR_STRING     '默认网关地址链表
        Public DhcpServer As IP_ADDR_STRING     'DHCP服务器地址,DhcpEnabled=TRUE时有效
        Public HaveWins As Byte      '是否启用WINS(Windows Internet Name Service)
        Public PrimaryWinsServer As IP_ADDR_STRING      '主WINS地址
        Public SecondaryWinsServer As IP_ADDR_STRING        '辅WINS地址
        Public LeaseObtained As Integer    '向DHCP服务器租用IP地址的时间,DhcpEnabled=TRUE时有效
        Public LeaseExpires As Integer '向DHCP服务器租用IP地址到期时间,DhcpEnabled=TRUE时有效
    End Structure

    'Public Declare Function AddIPAddress Lib "iphlpapi.dll" (ByVal Address As Long, ByVal IpMask As Long, ByVal Ifindex As Long, NTEContext As Long, NTEInstance As Long) As Long
    'Public Declare Function DeleteIPAddress Lib "iphlpapi.dll" (ByVal NTEContext As Long) As Long

    Public Declare Function AddIPAddress Lib "iphlpapi.dll" (
                                                            ByVal Address As Integer,
                                                            ByVal IpMask As Integer,
                                                            ByVal Ifindex As Integer,
                                                            ByRef NTEContext As IntPtr,
                                                            ByRef NTEInstance As IntPtr
                                                            ) As Integer
    Public Declare Function DeleteIPAddress Lib "iphlpapi.dll" (ByVal NTEContext As Integer) As Integer

    Private Declare Function GetAdaptersInfo Lib "iphlpapi.dll" (ByRef IpAdapterInfo As IntPtr, ByRef pOutBufLen As Integer) As Integer
    Private Declare Function GetAdaptersInfo Lib "iphlpapi.dll" (ByVal IpAdapterInfo() As Byte, ByRef pOutBufLen As Integer) As Integer


    Public Declare Function inet_addr Lib "wsock32.dll" (ByVal cp As String) As Integer

    Public Structure IPInfo
        Dim dwIndex As Integer  '适配器索引号
        Dim ip As String        'IP地址
        Dim mask As String      '子网掩码地址
        Dim Context As Integer  '网络IP地址标识,删除的时候使用
    End Structure

    Private Sub btnShowIPs_Click(sender As Object, e As EventArgs) Handles btnShowIPs.Click
        TextBox1.Text &= "当前IP列表:" & vbCrLf
        Call showIP()
    End Sub

    Private Sub btnAddIP_Click(sender As Object, e As EventArgs) Handles btnAddIP.Click

        TextBox1.Text &= "增加后:" & vbCrLf

        Dim IPAddr As Integer = inet_addr(txtAddIP.Text)
        Dim IpMask As Integer = inet_addr("255.255.255.0")
        '我这台电脑是8,这里简化直接写在代码内
        Dim Ifindex As Integer = 8

        Dim NTEContext As IntPtr
        Dim NTEInstance As IntPtr
        Dim returnValue As Integer

        '需要管理员权限,否侧会返回代码5
        returnValue = AddIPAddress(IPAddr, IpMask, Ifindex, NTEContext, NTEInstance)
        If returnValue <> 0 Then
            TextBox1.Text &= "发生错误:" & getErr(returnValue) & vbCrLf
            Exit Sub
        End If

        Call showIP()
    End Sub

    Private Sub showIP()
        Dim lstIPinfo As New List(Of IPInfo)
        lstIPinfo = getIPInfo()
        For i As Integer = 0 To lstIPinfo.Count - 1
            TextBox1.Text &= lstIPinfo(i).dwIndex & ":" & lstIPinfo(i).ip & " " & lstIPinfo(i).mask & " " & lstIPinfo(i).Context & vbCrLf
        Next
    End Sub

    Private Function getIPInfo() As List(Of IPInfo)
        Dim lstIPinfo As New List(Of IPInfo)

        Dim ptrIpAdapterInfo As IntPtr = IntPtr.Zero
        Dim lenOutBufLen As Integer

        Dim returnValue As Integer
        returnValue = GetAdaptersInfo(ptrIpAdapterInfo, lenOutBufLen)
        Dim bufferIAI(lenOutBufLen - 1) As Byte
        returnValue = GetAdaptersInfo(bufferIAI, lenOutBufLen)


        Dim iai As New IP_ADAPTER_INFO
        Dim sizeIAI As Integer = Marshal.SizeOf(iai)
        Dim ptrIAI As New IntPtr
        ptrIAI = Marshal.AllocHGlobal(sizeIAI)

        Marshal.Copy(bufferIAI, 0, ptrIAI, sizeIAI)
        iai = Marshal.PtrToStructure(ptrIAI, GetType(IP_ADAPTER_INFO))

        Do While True

            '获得IP地址
            Dim iasIpAddress As IP_ADDR_STRING = iai.IpAddressList

            '获得IP地址列表
            Do While True
                Dim singleIpInfo As IPInfo
                singleIpInfo.dwIndex = iai.Index

                singleIpInfo.ip = (New String(iasIpAddress.IpAddress)).Replace(vbNullChar, "")
                singleIpInfo.mask = (New String(iasIpAddress.IpMask)).Replace(vbNullChar, "")
                singleIpInfo.Context = iasIpAddress.Context

                lstIPinfo.Add(singleIpInfo)
                If iasIpAddress.Next = IntPtr.Zero Then
                    Exit Do
                End If
                iasIpAddress = Marshal.PtrToStructure(iasIpAddress.Next, GetType(IP_ADDR_STRING))
            Loop

            If iai.Next = IntPtr.Zero Then
                Exit Do
            End If
            iai = Marshal.PtrToStructure(iai.Next, GetType(IP_ADAPTER_INFO))
        Loop

        Return lstIPinfo
    End Function

    Private Function getErr(ByVal errorcode As Integer) As String
        Select Case errorcode
            Case 5
                Return "ERROR_ACCESS_DENIED 访问被拒绝"
            Case 6
                Return "ERROR_INVALID_HANDLE 句柄无效,需要管理员权限"
            Case 31
                Return "ERROR_GEN_FAILURE 连接到系统的设备不工作。尤其是Address参数中某些值造成此错误, 例如IPv4地址被设为广播地址"
            Case 50
                Return "ERROR_NOT_SUPPORTED 当前Windows版本不支持。"
            Case 55
                Return "ERROR_DEV_NOT_EXIST IfIndex参数指定的适配器不存在"
            Case 87
                Return "ERROR_INVALID_PARAMETER 参数无效"
            Case 1221
                Return "ERROR_DUP_DOMAINNAME 要添加的IPv4地址已存在"
            Case Else
                Return "其它错误"
        End Select
    End Function

    Private Sub Button2_Click(sender As Object, e As EventArgs) Handles btnDelIP.Click
        TextBox1.Text &= "删除后:" & vbCrLf

        Dim NTEContext As Integer
        NTEContext = Integer.Parse(txtDELIPcontext.Text)
        Dim returnValue As Integer

        '需要管理员权限,否侧会返回代码5
        returnValue = DeleteIPAddress(NTEContext)
        If returnValue <> 0 Then
            TextBox1.Text &= "发生错误,错误代码 " & returnValue & vbCrLf
            Exit Sub
        End If
        Call showIP()
    End Sub


End Class

 

由于.net平台下C#和vb.NET很相似,本文也可以为C#爱好者提供参考。

学习更多vb.net知识,请参看 vb.net 教程 目录

以上是关于vb.net 第二十一节 增加和删除一个IP地址的主要内容,如果未能解决你的问题,请参考以下文章

vb.net 第十一节 获取当前计算机的IP信息 GetIpStatistics

第二十一节——SpringMVC拦截器入门

centos mysql 优化 第二十一节课

第二十一节,使用TensorFlow实现LSTM和GRU网络

第二十一节 面向对象 构造器详解 创建对象内存分析

第二十一节 jQuery循环