TCP/IP實驗獲取主機網絡卡資訊
阿新 • • 發佈:2019-01-25
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using SharpPcap; using PacketDotNet; using SharpPcap.LibPcap; namespace Text { public partial class Form1 : Form { CaptureDeviceList device_list; public Form1() { InitializeComponent(); device_list = GetDeviceList(); } /// <summary> /// 獲得當前的裝置列表(網絡卡) /// </summary> /// <returns></returns> public CaptureDeviceList GetDeviceList() { // Print SharpPcap version string ver = SharpPcap.Version.VersionString; this.richTextBox1.Text = string.Format("SharpPcap {0}, Device List\n", ver); try { // Retrieve the device list CaptureDeviceList device_list = CaptureDeviceList.Instance; // If no devices were found print an error if (device_list.Count < 1) { this.richTextBox1.Text += "No devices were found on this machine\n"; return null; } this.richTextBox1.Text += "\nThe following devices are available on this machine:\n"; this.richTextBox1.Text +="----------------------------------------------------\n"; // Print out the available network devices foreach (ICaptureDevice dev in device_list) this.richTextBox1.Text += string.Format("\n名稱:{0}\n閘道器:{1}\n描述:{2}\n", ((PcapDevice)dev).Interface.FriendlyName, ((PcapDevice)dev).Interface.GatewayAddress, ((PcapDevice)dev).Interface.Description); return device_list; } catch (System.Exception ex) { MessageBox.Show(ex.ToString()); return null; } } } }
實驗結果
SharpPcap 採用了分層結構,在最頂層的是幾個管理所有裝置的類:
CaptureDeviceList——包含系統中所有裝置的列表
ICaptureDevice——所有繼承 ICaptureDevice 介面的裝置
通過執行下面一行程式碼,可以輕鬆獲得所有本機的所有網絡卡裝置:
CaptureDeviceListdevice_list = CaptureDeviceList.Instance;
在獲得網絡卡裝置以後,通過下面的 foreach 迴圈,就能將裝置資訊輸出到RichTextBox 中:
foreach (ICaptureDevice dev in
this.richTextBox1.Text+= string.Format("\n名稱:{0}\n閘道器:{1}\n描述:{2}\n", ((PcapDevice)dev).Interface.FriendlyName,((PcapDevice)dev).Interface.GatewayAddress, ((PcapDevice)dev).Interface.Description);