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 indevice_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);