vb.net 第六节 获取当前UDP连接情况 GetUdpTable
Posted VB.Net
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了vb.net 第六节 获取当前UDP连接情况 GetUdpTable相关的知识,希望对你有一定的参考价值。
版权声明:本文为博主原创文章,转载请在显著位置标明本文出处以及作者网名,未经作者允许不得用于商业目的。
Imports System.Runtime.InteropServices
Public Class Form7
'typedef struct _MIB_UDPTABLE
' DWORD dwNumEntries;
' MIB_UDPROW table[ANY_SIZE];
' MIB_UDPTABLE, *PMIB_UDPTABLE;
'typedef struct _MIB_UDPROW
' DWORD dwLocalAddr;
' DWORD dwLocalPort;
' MIB_UDPROW, *PMIB_UDPROW;
'Type MIB_UDPTABLE
' dwNum_Of_Entries As Long '当前 UDP连接的总数
' UDP_Table() As MIB_UDPROW '指向包含MIB_UDPROW类型的指针
'End Type
'Type MIB_UDPROW
' dwLocalAddr As Long '本地IP
' dwLocalPort As Long '本地端口
'End Type
'Private Declare Function GetUdpTable Lib "iphlpapi.dll" (ByRef pTcpTable As MIB_UDPTABLE, ByRef pdwSize As Long, ByVal bOrder As Long) As Long
Structure MIB_UDPTABLE
Dim dwNum_Of_Entries As Integer '当前 UDP连接的总数
Dim UDP_Table() As MIB_UDPROW '指向包含MIB_UDPROW类型的指针
End Structure
Structure MIB_UDPROW
Dim dwLocalAddr As Integer '本地IP
Dim dwLocalPort As Integer '本地端口
End Structure
Private Declare Function GetUdpTable Lib "iphlpapi.dll" (ByRef pUdpTable As IntPtr, ByRef pdwSize As Integer, ByVal bOrder As Integer) As Integer
Private Declare Function GetUdpTable Lib "iphlpapi.dll" (ByVal pUdpTable() As Byte, ByRef pdwSize As Integer, ByVal bOrder As Integer) As Integer
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim pMIB_UDPTABLE As IntPtr = IntPtr.Zero
Dim dwSize As Integer
Dim returnValue As Integer
'第一次调用,返回122:ERROR_INSUFFICIENT_BUFFER,缓冲区大小不足
'pdwSize参数返回实际需要的字节大小
returnValue = GetUdpTable(pMIB_UDPTABLE, dwSize, True)
Dim bufferMIB_UDPTABLE(dwSize - 1) As Byte
'第二次调用获得数据
returnValue = GetUdpTable(bufferMIB_UDPTABLE, dwSize, True)
'获得数量
Dim bytesNumEntries(3) As Byte
Array.Copy(bufferMIB_UDPTABLE, 0, bytesNumEntries, 0, 4)
Dim size As Integer = Marshal.SizeOf(bytesNumEntries(0)) * bytesNumEntries.Length
Dim ptrNumEntries As IntPtr = Marshal.AllocHGlobal(size)
Marshal.Copy(bytesNumEntries, 0, ptrNumEntries, 4)
Dim NumEntries As Integer
NumEntries = Marshal.ReadInt32(ptrNumEntries)
Dim MIBUr As MIB_UDPROW
Dim sizeMIBTr As Integer = Marshal.SizeOf(MIBUr)
For i As Integer = 0 To NumEntries - 1
Dim pMIB_TCPROW As New IntPtr
pMIB_TCPROW = Marshal.AllocHGlobal(sizeMIBTr)
Marshal.Copy(bufferMIB_UDPTABLE, 4 + sizeMIBTr * i, pMIB_TCPROW, sizeMIBTr)
MIBUr = Marshal.PtrToStructure(pMIB_TCPROW, GetType(MIB_UDPROW))
TextBox1.Text &= IntToIP(MIBUr.dwLocalAddr) & ":" & MIBUr.dwLocalPort & vbCrLf
Next
End Sub
'Integer型IP转字符串
Private Function IntToIP(ByVal intAddr As Integer) As String
Dim bteIp() As Byte
bteIp = BitConverter.GetBytes(intAddr)
Dim ip As String = ""
For i As Integer = 0 To bteIp.Length - 1
ip &= bteIp(i).ToString & "."
Next
Return ip.Substring(0, ip.Length - 1)
End Function
End Class
由于.net平台下C#和vb.NET很相似,本文也可以为C#爱好者提供的参考。
学习更多vb.net知识,请参看 vb.net 教程 目录
以上是关于vb.net 第六节 获取当前UDP连接情况 GetUdpTable的主要内容,如果未能解决你的问题,请参考以下文章
vb.net 第十六节 获取本机IP 路由表 GetIpForwardTable