using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SharpPcap;
using SharpPcap.Protocols;
using SharpPcap.Packets;
using SharpPcap.Util;
using System.Net;
namespace ArpSender
{
class Program
{
static IPAddress localIP;
static IPAddress targetIP;
//初始化ARP请求包的方法
static ARPPacket getARPPacket(System.Net.IPAddress targetIP, string localMAC, System.Net.IPAddress localIP)
{
ARPPacket arp = new ARPPacket(14, new byte[60]);
arp.ARPHwLength = 6;
arp.ARPHwType = ARPFields_Fields.ARP_ETH_ADDR_CODE;
arp.ARPProtocolLength = 4;
arp.ARPProtocolType = ARPFields_Fields.ARP_IP_ADDR_CODE;
arp.ARPSenderHwAddress = localMAC;
arp.ARPSenderProtoAddress = localIP;
arp.SourceHwAddress = localMAC;
arp.EthernetProtocol = EthernetPacket.EtherType.ARP;
arp.ARPOperation = ARPFields_Fields.ARP_OP_REQ_CODE;
arp.ARPTargetHwAddress = "00:00:00:00:00:00";
arp.ARPTargetProtoAddress = targetIP;
arp.DestinationHwAddress = "ff:ff:ff:ff:ff:ff";
return arp;
}
static void Main(string[] args)
{
//获得网络设备列表,并选择将要发送请求的设备
List<PcapDevice> devices = SharpPcap.Pcap.GetAllDevices();
foreach (PcapDevice d in devices)
{
Console.WriteLine(d.Name);
Console.WriteLine(d.Description);
foreach (Pcap.PcapAddress addr in d.Addresses)
{
Console.WriteLine(addr.ToString());
}
Console.WriteLine();
}
Console.WriteLine("请选择将要监控的设备:");
int deviceIndex = Console.Read() - 48;
PcapDevice device = devices[deviceIndex];
localIP = device.Addresses[0].Addr.ipAddress;
targetIP = IPAddress.Parse("192.168.1.1");
string localMac = "00-1B-B9-DC-56-57";
device.Open(false,-1);
//为网络设备增加包到达事件
device.OnPacketArrival += new Pcap.PacketArrivalEvent(device_OnPacketArrival);
device.SetFilter("arp");
//初始化一个ARP请求包
ARPPacket p = getARPPacket(targetIP, localMac, localIP);
Console.WriteLine(DateTime.Now);
Console.WriteLine("发送ARP包:" + p);
//发送ARP请求包
device.SendPacket(p);
device.StartCapture();
Console.ReadKey();
device.StopCapture();
device.Close();
}
//检测到包到达时进行的操作
static void device_OnPacketArrival(object sender, Packet packet)
{
ARPPacket arp = (ARPPacket)packet;
if (arp.ARPOperation == 2 & arp.ARPSenderProtoAddress.Equals(targetIP) & arp.ARPTargetProtoAddress.Equals(localIP))
{
Console.WriteLine(DateTime.Now);
Console.WriteLine("接收回复包:" + arp);
}
}
}
}