我正在尝试使用vb.net开发管理防火墙端口的代码。第一部分是列出所有启用的端口。所以我正在尝试这段代码:
Function portsList()
Dim ports As INetFwOpenPorts
Dim port As INetFwOpenPort
Dim myPorts() As INetFwOpenPorts
Dim NetFwMgrType As Type = Type.GetTypeFromProgID("HNetCfg.FwMgr", False)
Dim mgr As INetFwMgr = DirectCast(Activator.CreateInstance(NetFwMgrType), INetFwMgr)
ports = DirectCast(mgr.LocalPolicy.CurrentProfile.GloballyOpenPorts, INetFwOpenPorts)
Dim enumerate As System.Collections.IEnumerator = ports.GetEnumerator()
Dim i As Integer
While enumerate.MoveNext()
port = DirectCast(enumerate.Current, INetFwOpenPort)
myPorts(i) = port
i += 1
End While
Dim portAsString() As String
For j As Integer = 0 To i
portAsString(j) = myPorts(j).ToString
Next
Return portAsString
End Function
Private Sub Button4_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button4.Click
Dim ports() As String = portsList()
Dim n As String = ports.Length
Dim newString As String = ""
For h As Integer = 0 To n
newString = ports(h) & vbNewLine
Next
RichTextBox1.Text = newString
End Sub
点击Richtextbox1
后,我想要列出Button4
中的所有端口。我得到的错误是:
NullReferenceException是unHandled。你调用的对象是空的。
我是Vb的新手,我怎么能克服这个?
答案 0 :(得分:0)
试试这个:
For port As Integer = 1 to maxPorts
Dim host As String = "192.168.1.7"
Dim hostadd As Net.IPAddress = Net.Dns.GetHostEntry(host).AddressList(0)
Dim EPhost As New Net.IPEndPoint(hostadd, port)
Dim s As New Net.Sockets.Socket(Net.Sockets.AddressFamily.InterNetwork, Net.Sockets.SocketType.Stream, Net.Sockets.ProtocolType.Tcp)
Try
s.Connect(EPhost)
Catch
End Try
If s.Connected Then
'Port opened
Else
'Port closed
End If
Next
Here你有完整的项目。