[C#][VB.NET]顯示出目前網際網路連線狀態的小程式

  • 20395
  • 0
  • 2010-08-02

顯示出目前網際網路連線狀態,類似netstat.exe程式的功能

說明

在藍色小舖中,有人問起如何顯示電腦目前的連線狀態,功能類似netstat指令的功能,這部份的功能可以透過

System.Net.NetworkInformation.TcpConnectionInformation : 提供本機電腦上的傳輸控制通訊協定 (TCP) 連線資訊。

可以參考MSDN http://msdn.microsoft.com/zh-tw/library/system.net.networkinformation.tcpconnectioninformation

以下程式碼,將 TcpConnectionInformation 放入 Timer_Tick 中,定時更新電腦目前的連線狀態

C# 程式碼

01 using System;
02 using System.Collections.Generic;
03 using System.ComponentModel;
04 using System.Data;
05 using System.Drawing;
06 using System.Text;
07 using System.Windows.Forms;

08
09 namespace WindowsApplication27
10 {
11     public partial class Form1 : Form
12     {
13         public Form1()
14         {
15             InitializeComponent();
16         }

17
18         private void Form1_Load(object sender, EventArgs e)
19         {
20             timer1.Interval = 100;
21             timer1.Enabled = true;
22         }

23
24         private void timer1_Tick(object sender, EventArgs e)
25         {
26             System.Text.StringBuilder builder = new System.Text.StringBuilder();
27             System.Net.NetworkInformation.IPGlobalProperties ipProps = System.Net.NetworkInformation.IPGlobalProperties.GetIPGlobalProperties();
28             foreach (System.Net.NetworkInformation.TcpConnectionInformation connection in ipProps.GetActiveTcpConnections())
29             {
30                 builder.AppendFormat("{0} -> {1} - {2}{3}", connection.LocalEndPoint, connection.RemoteEndPoint, connection.State, Environment.NewLine);
31             }

32             textBox1.Text = builder.ToString();  
33         }

34     }

35 }

 

 

VB.NET程式碼

01 Public Class Form1
02
03     Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
04         Timer1.Interval = 100
05         Timer1.Enabled = True
06     End Sub

07
08     Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
09         Dim builder As New System.Text.StringBuilder
10         Dim ipProps As System.Net.NetworkInformation.IPGlobalProperties = System.Net.NetworkInformation.IPGlobalProperties.GetIPGlobalProperties()
11         For Each connection As System.Net.NetworkInformation.TcpConnectionInformation In ipProps.GetActiveTcpConnections
12             builder.AppendFormat("{0} -> {1} - {2}{3}", connection.LocalEndPoint, connection.RemoteEndPoint, connection.State, Environment.NewLine)
13         Next
14         TextBox1.Text = builder.ToString
15     End Sub

16 End Class

 

執行結果

參考

http://www.blueshop.com.tw/board/show.asp?subcde=BRD20090418195852AVQ&fumcde=

 

範例下載

[VB.NET]顯示出目前網際網路連線狀態的小程式.rar