不得不佩服SharpPcap的强大,很多我们需要网络协议,枚举等已经非常完善了
一个简单的代码,获取网络设备列表
//获取网络设备列表
NetworkDeviceList crazyCoderDeviceList = IPHelper.GetAllDevices();
//绑定到datagrideview
dgvMain.DataSource = crazyCoderDeviceList;
return;
发送数据包源码,仅供示例用
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Tamir.IPLib;
using Tamir.IPLib.Packets;
using Tamir.IPLib.Protocols;
using Tamir.IPLib.Util;
using Test;
namespace CrazyCoder.Cn.Test
{
public partial class CrazyCoder_PcapTest : Form
{
static int lLen = EthernetFields_Fields.ETH_HEADER_LEN;
static string destIP = "192.168.1.3";
static string destMAC = "00-E0-A0-06-F3-22";
static int destPort = 80;
static int sourcePort = 2222;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
//获取网络设备列表
NetworkDeviceList crazyCoderDeviceList = IPHelper.GetAllDevices();
//绑定到datagrideview
dgvMain.DataSource = crazyCoderDeviceList;
//实例化网卡实例
NetworkDevice crazyCoderDev = new NetworkDevice("{D8E51B8B-DF57-4CD5-A36A-06C6B9391666}");
byte[] bytes = new byte[54];
TCPPacket tcp = new TCPPacket(lLen, bytes, true);
//枚举
tcp.SourceHwAddress = crazyCoderDev.MacAddress; //本机MAC地址
tcp.DestinationHwAddress = destMAC; //目的MAC地址
tcp.EthernetProtocol = EthernetProtocols_Fields.IP;
tcp.DestinationAddress = destIP;
tcp.SourceAddress = crazyCoderDev.IpAddress;
//tcp.SourceAddress = "192.168.1.98";
tcp.IPProtocol = IPProtocols_Fields.TCP;
tcp.TimeToLive = 20;
tcp.Id = 100;
tcp.Version = 4;
tcp.IPTotalLength = bytes.Length - lLen;
tcp.IPHeaderLength = IPFields_Fields.IP_HEADER_LEN;
//TCP
tcp.SourcePort = sourcePort;
tcp.DestinationPort = destPort;
tcp.Syn = true;
tcp.WindowSize = 555;
tcp.AcknowledgementNumber = 1000;
tcp.SequenceNumber = 1000;
tcp.TCPHeaderLength = TCPFields_Fields.TCP_HEADER_LEN;
//tcp.SetData( System.Text.Encoding.ASCII.GetBytes("HELLO CrazyCoder.cn") );
tcp.ComputeIPChecksum();
tcp.ComputeTCPChecksum();
crazyCoderDev.PcapOpen(true, 20);
crazyCoderDev.PcapSetFilter("ip src " + destIP + " and ip dst " +
crazyCoderDev.IpAddress + " and tcp src port " + destPort + " and tcp dst port " + sourcePort);
//发送数据包
Console.Write("Sending packet: " + tcp + "...");
crazyCoderDev.PcapSendPacket(tcp);
Console.WriteLine("Packet sent.");
Packet reply;
while ((reply = crazyCoderDev.PcapGetNextPacket()) == null) ;
string str = "";
str += "Reply received: " + reply;
crazyCoderDev.PcapClose();
MessageBox.Show(str);
}
}
}