private void start_Click(object sender, EventArgs e) { if (DeviceList.SelectedItem == null) MessageBox.Show("Please choose a device to monitor"); else if (CaptureOngoing) MessageBox.Show("Capturing..."); else { CaptureOngoing = true; start.Enabled = false; reset.Enabled = true; pause.Enabled = true; save.Enabled = false; export.Enabled = false; device = devices[DeviceIndex]; device.OnPacketArrival += new PacketArrivalEventHandler(device_OnPacketArrival);// Registers new function to the event handler. int readTimeout = 10; device.Open(DeviceMode.Promiscuous, readTimeout);// Sets monitoring mode to promiscuous mode. device.Filter = FilterRule; FilterExp.Text = (FilterRule == "") ? "all pass" : FilterRule; device.StartCapture(); } }
private string OpenCaptureFile(string FilePath) { try { device = new CaptureFileReaderDevice(FilePath); device.Open(); return(null); } catch (Exception e) { return($"Error opening capture ({FilePath}): {e.ToString()}"); } }
private static void CaptureFlowSend(string IP, int portID, int deviceID) { ICaptureDevice device = CaptureDeviceList.New()[deviceID]; device.OnPacketArrival += new PacketArrivalEventHandler(Device_OnPacketArrivalSend); int readTimeoutMilliseconds = 1000; device.Open(DeviceMode.Promiscuous, readTimeoutMilliseconds); string filter = "src host " + IP + " and src port " + portID; device.Filter = filter; device.StartCapture(); }
private void CmbDevices_SelectedIndexChanged(object sender, EventArgs e) { device = devices[cmbDevices.SelectedIndex]; cmbDevices.Text = device.Description; //Register the handler function on the 'packet arrival' event device.OnPacketArrival += new SharpPcap.PacketArrivalEventHandler(device_OnPacketArrival); //Open the device for capture int readTimeoutMilliseconds = 1000; device.Open(DeviceMode.Promiscuous, readTimeoutMilliseconds); }
public void listingPackets(ICaptureDevice dev) { device = dev; int readTimeoutMilliseconds = 1000; backgroundThread = new Thread(BackgroundThread); backgroundThread.Start(); device.OnPacketArrival += new PacketArrivalEventHandler(device_OnPacketArrival); device.Open(DeviceMode.Promiscuous, readTimeoutMilliseconds); device.StartCapture(); }
private void cmbDevices_SelectedIndexChanged(object sender, EventArgs e) { device = devices[cmbDevices.SelectedIndex]; cmbDevices.Text = device.Description; txtGUID.Text = device.Name; //register our handler function to the packet arrival event device.OnPacketArrival += new SharpPcap.PacketArrivalEventHandler(device_OnPacketArrival); int readTimeoutMilliseconds = 1000; device.Open(DeviceMode.Promiscuous, readTimeoutMilliseconds); }
private static async Task MonitoringMode(bool on = true) { if (on) { Console.WriteLine($"-- Enabling Monitor mode on {Device.Name}"); var wifiOffResult = await CliWrap.Cli.Wrap("sudo").WithArguments($"nmcli radio wifi off").WithValidation(CliWrap.CommandResultValidation.None).ExecuteAsync(); Console.WriteLine($"-- Disabling the WiFi chip took {wifiOffResult.RunTime.TotalMilliseconds}ms"); var wifiOnResult = await CliWrap.Cli.Wrap("sudo").WithArguments($"nmcli radio wifi on").WithValidation(CliWrap.CommandResultValidation.None).ExecuteAsync(); Console.WriteLine($"-- Enabling the WiFi chip took {wifiOnResult.RunTime.TotalMilliseconds}ms"); var wwanOnResult = await CliWrap.Cli.Wrap("sudo").WithArguments($"nmcli radio wwan on").WithValidation(CliWrap.CommandResultValidation.None).ExecuteAsync(); Console.WriteLine($"-- Enabling the modem took {wwanOnResult.RunTime.TotalMilliseconds}ms"); var lteUpResult = await CliWrap.Cli.Wrap("sudo").WithArguments($"nmcli connection PublicIP up").WithValidation(CliWrap.CommandResultValidation.None).ExecuteAsync(); Console.WriteLine($"-- Connecting to 4G took {lteUpResult.RunTime.TotalMilliseconds}ms"); var devDownResult = await CliWrap.Cli.Wrap("sudo").WithArguments($"ip link set {Device.Name} down").WithValidation(CliWrap.CommandResultValidation.None).ExecuteAsync(); Console.WriteLine($"-- Taking down {Device.Name} took {devDownResult.RunTime.TotalMilliseconds}ms"); var modeResult = await CliWrap.Cli.Wrap("sudo").WithArguments($"iwconfig {Device.Name} mode Monitor").WithValidation(CliWrap.CommandResultValidation.None).ExecuteAsync(); Console.WriteLine($"-- Switching {Device.Name} to Monitor Mode took {modeResult.RunTime.TotalMilliseconds}ms"); var setMacResult = await CliWrap.Cli.Wrap("sudo").WithArguments($"ip link set dev {Device.Name} address DE:AD:BE:EF:13:37").WithValidation(CliWrap.CommandResultValidation.None).ExecuteAsync(); Console.WriteLine($"-- Setting {Device.Name} MAC to DE:AD:BE:EF:13:37 took {setMacResult.RunTime.TotalMilliseconds}ms"); var devUpResult = await CliWrap.Cli.Wrap("sudo").WithArguments($"ip link set {Device.Name} up").WithValidation(CliWrap.CommandResultValidation.None).ExecuteAsync(); Console.WriteLine($"-- Bringing up {Device.Name} took {devUpResult.RunTime.TotalMilliseconds}ms"); BeaconMonitor = new BeaconMonitor("beacons.log"); ProbeMonitor = new ProbeMonitor("probes.log"); Device.OnPacketArrival += Device_OnPacketArrival; Device.Open(DeviceMode.Promiscuous, 2000, MonitorMode.Inactive); Device.StartCapture(); Console.CancelKeyPress += async(a, b) => await MonitoringMode(false); } else { Console.WriteLine($"-- Disabling Monitor mode on {Device.Name}"); Device.StopCapture(); Console.WriteLine("-- Capture stopped."); await CliWrap.Cli.Wrap("sudo").WithArguments($"ip link set {Device.Name} down").WithValidation(CliWrap.CommandResultValidation.None).ExecuteAsync(); await CliWrap.Cli.Wrap("sudo").WithArguments($"iwconfig {Device.Name} mode Managed").WithValidation(CliWrap.CommandResultValidation.None).ExecuteAsync(); await CliWrap.Cli.Wrap("sudo").WithArguments($"ip link set dev {Device.Name} address 12:7:00:00:00:01").WithValidation(CliWrap.CommandResultValidation.None).ExecuteAsync(); await CliWrap.Cli.Wrap("sudo").WithArguments($"ip link set {Device.Name} up").WithValidation(CliWrap.CommandResultValidation.None).ExecuteAsync(); } }
static void Main(string[] args) { if (args.Length == 0) { //Console.WriteLine("no Key Word.. by by.."); //Environment.Exit(0); argLayerType = "t"; } else { argLayerType = args[0]; } var devices = CaptureDeviceList.Instance; int numberDevice = -1; foreach (var dev in devices) { Console.WriteLine(dev); } Console.WriteLine("enter number device.. (see flags) "); numberDevice = Convert.ToInt32(Console.ReadLine()); if (numberDevice != -1) { ICaptureDevice Device = devices[numberDevice]; Encoding EncodUnicode = Encoding.Unicode; //KeyWord = EncodUnicode.GetBytes(args[0]); Device.OnPacketArrival += new SharpPcap.PacketArrivalEventHandler(device_OnPaketArrival); Device.Open(DeviceMode.Normal); Console.WriteLine("Listein {0}", Device.Description); Device.StartCapture(); Console.ReadLine(); Device.StopCapture(); Device.Close(); } else { Console.WriteLine("Device not active.."); Environment.Exit(0); } }
public void CaptureFlowSend(string IP, int deviceID) { ICaptureDevice device = (ICaptureDevice)CaptureDeviceList.New()[deviceID]; device.OnPacketArrival += new PacketArrivalEventHandler(device_OnPacketArrivalSend); int readTimeoutMilliseconds = 100; device.Open(DeviceMode.Promiscuous, readTimeoutMilliseconds); string filter = "src host " + IP; device.Filter = filter; device.StartCapture(); ProcInfo.CapDevs.Add(device); }
/** * Set the capture device */ private void setDevice(ICaptureDevice dev) { device = dev; cmbDevices.Text = device.Description; txtGUID.Text = device.Name; // Register handler function to the 'packet arrival' event device.OnPacketArrival += new SharpPcap.PacketArrivalEventHandler(device_onPacketArrival); // Open device for capturing int readTimeoutMilliseconds = 1000; device.Open(DeviceMode.Promiscuous, readTimeoutMilliseconds); }
private void PacketCaptureThreadStart() { //Open the device captureDevice.Open(); //Set filter to capture only port 28960 captureDevice.Filter = "udp port 28960"; //Add the event handler captureDevice.OnPacketArrival += new PacketArrivalEventHandler(OnPacketArrival); //Start capturing captureDevice.StartCapture(); }
public void CaptureFlowRecv(string IP, int portID, int deviceID) { ICaptureDevice device = CaptureDeviceList.New()[deviceID]; device.OnPacketArrival += new PacketArrivalEventHandler(device_OnPacketArrivalRecv); int readTimeoutMilliseconds = 0; device.Open(DeviceMode.Promiscuous, readTimeoutMilliseconds); string filter = "dst host " + IP + " and dst port " + portID; device.Filter = filter; device.StartCapture(); ProcInfo.CapDevs.Add(device); }
static void Start() { pid = Process.GetProcessesByName("viber")[0].Id; var proc = new Process { StartInfo = new ProcessStartInfo { FileName = "netstat", Arguments = "-on", UseShellExecute = false, RedirectStandardOutput = true, CreateNoWindow = true } }; proc.Start(); Regex r = new Regex(@"\S+\s+(?<address>\S+)\s+\S+\s+\S+\s+(?<pid>\d+)"); while (!proc.StandardOutput.EndOfStream) { var res = r.Match(proc.StandardOutput.ReadLine()); if (res.Success) { if (res.Groups["pid"].Value == Process.GetProcessesByName("viber")[0].Id.ToString()) { // var pid = int.Parse(res.Groups["pid"].Value); var address = res.Groups["address"].Value; Ports.Add(new Ports() { num_port = address.ToString().Substring(address.ToString().IndexOf(':') + 1, address.ToString().Length - address.ToString().IndexOf(':') - 1) }); //address.ToString().Substring(address.ToString().IndexOf(':')+1,address.ToString().Length-address.ToString().IndexOf(':')-1) Console.WriteLine("{0} - {1}", address, Process.GetProcessById(pid).ProcessName); } } } //Console.ReadKey(); // метод для получения списка устройств CaptureDeviceList deviceList = CaptureDeviceList.Instance; // выбираем первое устройство в спсике (для примера) captureDevice = deviceList[0]; // регистрируем событие, которое срабатывает, когда пришел новый пакет captureDevice.OnPacketArrival += new PacketArrivalEventHandler(Program_OnPacketArrival); // открываем в режиме promiscuous, поддерживается также нормальный режим captureDevice.Open(DeviceMode.Promiscuous, 1000); // начинаем захват пакетов captureDevice.Capture(); }
public ICaptureDevice enableARPPoison(int deviceID, string srcIP, string srcMAC, string dstIP, string dstMAC, string midIP, string midMAC) { if ((srcMAC.Length != 12 || dstMAC.Length != 12 || midMAC.Length != 12)) { return(null); } if (deviceID == 0) { return(null); } int mss = 1000; CaptureDeviceList devices = CaptureDeviceList.Instance; device = devices[deviceID - 1]; // Register our handler function to the // 'packet arrival' event device.OnPacketArrival += new SharpPcap.PacketArrivalEventHandler(device_OnPacketArrival); device.Open(DeviceMode.Promiscuous, 1000); breake = true; string t1 = dstIP; string t2 = srcIP; string t3 = midIP; string t4 = midMAC.ToUpper(); string t5 = dstMAC.ToUpper(); string t6 = srcMAC.ToUpper(); Thread arpenv = new Thread(() => { while (breake) { SendARPresponse(device, IPAddress.Parse(t1), IPAddress.Parse(t2), PhysicalAddress.Parse(t4), PhysicalAddress.Parse(t6)); SendARPresponse(device, IPAddress.Parse(t2), IPAddress.Parse(t1), PhysicalAddress.Parse(t4), PhysicalAddress.Parse(t5)); SendARPresponse(device, IPAddress.Parse(t1), IPAddress.Parse(t3), PhysicalAddress.Parse(t5), PhysicalAddress.Parse(t4)); //FIX MAC INTERNA DEL ROUTER SendARPresponse(device, IPAddress.Parse(t2), IPAddress.Parse(t3), PhysicalAddress.Parse(t6), PhysicalAddress.Parse(t4)); //FIX MAC INTERNA DE LA VICTIMA Thread.Sleep(mss); } Thread.CurrentThread.Abort(); }); arpenv.IsBackground = true; arpenv.Start(); return(device); }
// Send private void button9_Click(object sender, EventArgs e) { if (!start) { start = true; button1.Text = "Stop"; button12.Visible = false; button1.FlatAppearance.BorderColor = System.Drawing.Color.Red; catched = 0; device = list[comboBox1.SelectedIndex]; device.OnPacketArrival += new PacketArrivalEventHandler(capture_event5); device.Open(DeviceMode.Promiscuous); device.StartCapture(); } }
public void SendingPACKETS(ICaptureDevice device) { device.Open(); byte[] bytes = new byte[1];// GetRandomPacket(); try { device.SendPacket(bytes); Console.WriteLine("Packet sent"); } catch (Exception e) { Console.WriteLine(e.Message); } device.Close(); }
/// <summary> /// start listening for arriving packets /// </summary> public void startPacketListener() { if (device == null) { MessageBox.Show("no adapter selected"); return; // will throw null pointer exception } // Create listener device.OnPacketArrival += new PacketArrivalEventHandler(device_OnPacketArrival); device.Open(DeviceMode.Promiscuous, 1500); // 1.5 sec timeout device.StartCapture(); }
// Пинг private void button5_Click(object sender, EventArgs e) { f.Show(); start = true; button1.Text = "Stop"; button12.Visible = false; button1.FlatAppearance.BorderColor = System.Drawing.Color.Red; device = list[comboBox1.SelectedIndex]; device.OnPacketArrival += new PacketArrivalEventHandler(capture_event3); device.Open(DeviceMode.Promiscuous); t = new System.Timers.Timer(check * 1000); t.Elapsed += OnTimedEvent; t.Enabled = true; t.Start(); device.StartCapture(); }
// Open the interface to start capturing data using a BPF filter from sharppcap private void btnCapture_Click(object sender, EventArgs e) { if (cboInterfaces.SelectedIndex > -1) { _device = _devices[cboInterfaces.SelectedIndex]; _device.OnPacketArrival += device_OnPacketArrival; var readTimeoutMilliseconds = 1000; _device.Open(DeviceMode.Promiscuous, readTimeoutMilliseconds); var filter = "udp and src port 53"; _device.Filter = filter; _device.StartCapture(); btnCapture.Enabled = false; btnStop.Enabled = true; cboInterfaces.Enabled = false; } }
//选择网卡 private void comDeviceList_SelectedIndexChanged(object sender, EventArgs e) { device = CaptureDeviceList.Instance[comDeviceList.SelectedIndex]; device.Open(); string hostMAC = MacFormat(((SharpPcap.WinPcap.WinPcapDevice)device).MacAddress.ToString()); string hostIP = ((SharpPcap.WinPcap.WinPcapDevice)device).Addresses[1].Addr.ipAddress.ToString(); txtEhSourMac.Text = hostMAC; txtARPSourMac.Text = txtEhSourMac.Text; txtARPSourIP.Text = hostIP; txtInterval.Text = "5"; rdoResp.Checked = true; }
public void StartLimiter() { try { if (capturedevice != null) { capturedevice.Open(DeviceMode.Normal, 1); //test difference in performance between the two modes capturedevice.Filter = $"(ip and ether src {TargetMAC.ToLower()}) or (ip and ether src {GatewayMAC.ToLower()} and dst net {device.IP})"; //dotted macs Limiter(); } } catch (Exception) { } }
/// <summary> /// 加载capFile,但是仅仅检测是否可以成功加载 /// </summary> /// <param name="capFileName"></param> public static void LoadCapFile(string capFileName) { if (device != null) { device.Close(); } try { device = new CaptureFileReaderDevice(capFileName); device.Open(); } catch (Exception) { MessageBox.Show("Error while opening capFile"); return; } }
static void Main(string[] args) { dev = CaptureDeviceList.Instance[0]; dev.Open(DeviceMode.Normal); dev.Filter = "tcp"; dev.OnPacketArrival += new PacketArrivalEventHandler(dev_OnPacketArrival); dev.StartCapture(); Thread.Sleep(Timeout.Infinite); /*Console.In.ReadLine(); * dev.StopCapture(); * Console.Out.WriteLine("total:" + total); * Console.In.ReadLine();*/ }
//CODE FROM https://www.codeproject.com/Articles/12458/SharpPcap-A-Packet-Capture-Framework-for-NET - ACCESSED 03/02/2018 - HEAVILY MODIFIED static void PacketCollect(CaptureDeviceList DeviceList) { int BaselineLimiter = 1000; //CHANGE THIS VALUE TO DETERMINE SIZE OF BASELINE // Extract a device from the list ICaptureDevice device = DeviceList[0]; //<- VALUE OF 0 WILL USE FIRST DEVICE // Register our handler function to the 'packet arrival' event device.OnPacketArrival += new SharpPcap.PacketArrivalEventHandler(Device_OnPacketArrival); // Open the device for capturing int readTimeoutMilliseconds = 1000; device.Open(DeviceMode.Promiscuous, readTimeoutMilliseconds); if (CompareOrBaseline == false) { // Open the device for capturing // tcpdump filter to capture only TCP/IP packets Console.WriteLine("-- Listening on {0}, collecting " + BaselineLimiter + " packets. Press any key to terminate early.", device.Description); // Start capturing packets while (PacketCounter < BaselineLimiter) { RawCapture rawPacket = null; rawPacket = device.GetNextPacket(); //get the next packet if (rawPacket != null) //if there's actually a packet there { var decodedPacket = PacketDotNet.Packet.ParsePacket(rawPacket.LinkLayerType, rawPacket.Data); //parse the packet if (TextOutput == true) { Console.WriteLine("PACKET BEGIN..."); Console.WriteLine(decodedPacket.ToString()); AddToList(decodedPacket.ToString()); Console.WriteLine("...PACKET END"); } else if (TextOutput == false) { AddToList(decodedPacket.ToString()); //add to dictionary } ++PacketCounter; } } } else if (CompareOrBaseline == true) { device.Capture(); device.Close(); //never called } }
public void sniff() { r_id = 1; // Print SharpPcap version string ver = SharpPcap.Version.VersionString; Console.WriteLine("SharpPcap {0}, Example1.IfList.cs", ver); // Retrieve the device list devices = CaptureDeviceList.Instance; // If no devices were found print an error if (devices.Count < 1) { Console.WriteLine("No devices were found on this machine"); return; } Console.WriteLine("\nThe following devices are available on this machine:"); Console.WriteLine("----------------------------------------------------\n"); // Print out the available network devices foreach (ICaptureDevice dev in devices) Console.WriteLine("{0}\n", dev.ToString()); Console.Write("Hit 'Enter' to exit..."); // Console.ReadLine(); // Extract a device from the list device = devices[0]; // Register our handler function to the // 'packet arrival' event device.OnPacketArrival += new SharpPcap.PacketArrivalEventHandler(device_OnPacketArrival); // Open the device for capturing int readTimeoutMilliseconds = 1000; device.Open(DeviceMode.Promiscuous, readTimeoutMilliseconds); Console.WriteLine("-- Listening on {0}, hit 'Enter' to stop...", device.Description); // Start the capturing process device.StartCapture(); // Wait for 'Enter' from the user. //while (true) { }; }
private void btnStart_Click(object sender, EventArgs e) { if (txtBootstrap.Text == "" || !txtBootstrap.Text.Contains(";")) { MessageBox.Show("Please enter your bootstrap token. This can be found at http://www.mysite.com/gps/", "Required Field Notification", MessageBoxButtons.OK, MessageBoxIcon.Error); txtBootstrap.Focus(); return; } bootstrap = txtBootstrap.Text.Split(';'); bootstrap[0] = bootstrap[0].Trim(); bootstrap[1] = bootstrap[1].Trim(); try { IPAddress.Parse(bootstrap[1]); } catch (Exception ex2) { MessageBox.Show("Invalid bootstrap token. The IP Address was not found. This can be found at http://www.mysite.com/gps/", "Required Field Notification", MessageBoxButtons.OK, MessageBoxIcon.Error); txtBootstrap.Focus(); return; } if (cboInterfaces.SelectedIndex < 0 || cboInterfaces.SelectedItem.ToString() == "") { MessageBox.Show("Please select a valid Network Interface.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Hand); cboInterfaces.Focus(); return; } httpClient = new WebClient(); httpClient.Headers.Add("Connection: keep-alive"); device = this.devices[int.Parse(cboInterfaces.SelectedIndex.ToString())]; saveNetworkInterface(); device.OnPacketArrival += new PacketArrivalEventHandler(device_OnPacketArrival); device.Open(DeviceMode.Promiscuous, 1000); //device.Filter = String.Format("host {0} and less 84 and greater 82", bootstrap[1]); device.Filter = String.Format("host {0} and greater 28", bootstrap[1]); device.StartCapture(); lblStatus.Text = "Running"; lblStatus.ForeColor = System.Drawing.Color.ForestGreen; updateQMAP = new Thread(checkUpdate); updateQMAP.Start(); sendForeignEntityThread = new Thread(sendForeignEntities); sendForeignEntityThread.Start(); dropThread = new Thread(sendDropCoordinates); dropThread.Start(); }
} //End timer1 //**********Changing devices private void cmbDevices_SelectedIndexChanged(object sender, EventArgs e) { if (device != null) { device.Close(); } device = devices[cmbDevices.SelectedIndex]; cmbDevices.Text = device.Description; txtGUID.Text = device.Name; //Register our handler function to the 'packet arrival' event device.OnPacketArrival += new SharpPcap.PacketArrivalEventHandler(device_OnPacketArrival); //Open the device for capturing int readTimeoutMilliseconds = 1000; device.Open(DeviceMode.Promiscuous, readTimeoutMilliseconds); } //End cmbDevices_SelectedIndexChanged
public static void getPackets(ICaptureDevice currentInterface) { currentInterface.OnPacketArrival += new PacketArrivalEventHandler(device_onPacketArrival); try { currentInterface.Open(DeviceMode.Promiscuous, 3000); } catch (Exception ex) { Console.WriteLine("Please run this application as administrator or with sudo"); System.Environment.Exit(1); } currentInterface.Capture(); currentInterface.Close(); }
private void button1_Click(object sender, EventArgs e) { if (this.comboBox1.SelectedIndex >= 0) { try { //Register our handler function to the 'packet arrival' event _device = devices[this.comboBox1.SelectedIndex]; _device.OnPacketArrival += new PacketArrivalEventHandler(device_OnPacketArrival); _device.Open(); _device.Filter = textBox1.Text; for (int i = 0; i <= 5; i++) { PacketQueue[i].Clear(); } _device.StartCapture(); try { if (_Backgroundthread.IsAlive) { _Backgroundthread.Abort(); } } catch { } ThreadStart threadstart = new ThreadStart(Backgroundprocess); _Backgroundthread = new Thread(threadstart); _Backgroundthread.Start(); //开启后台线程 textBox1.ReadOnly = true; button2.Enabled = true; button1.Enabled = false; } catch (Exception ex) { MessageBox.Show("过滤规则错误!" + ex.Message, "警告!"); } } else { MessageBox.Show("请选择网卡!", "提示"); } }
private void deviceStartCapture() { if (device == null) { MessageBox.Show("请先选择网络设备!"); return; } // 开启分析线程 analyzeThread = new Thread(new ThreadStart(analyzeAndAppendData)); analyzeThread.IsBackground = true; analyzeThread.Start(); // 注册包到达事件处理句柄 device.OnPacketArrival += new SharpPcap.PacketArrivalEventHandler(device_OnPacketArrival); // 设置读超时时间,在此时间内如果没有收到包则停止捕获 int readTimeoutMilliseconds = 1000; // 当DeviceMode被设为Normal模式时,只捕捉以本地为源或目的的报文 // 设为Promiscuous(混杂)模式时,捕捉以流过网卡的报文 device.Open(DeviceMode.Promiscuous, readTimeoutMilliseconds); // 非阻塞,在另一个线程上开始捕获 device.StartCapture(); /* * while ((rawPacket = device.GetNextPacket()) != null) * { * if (index == 1000 || isStoped) * { * break; * } * * bufferList.Add(rawPacket); * sourceView.Rows.Add(gridViewInfo.getRowByRawPacket(rawPacket, index)); * * index++; * } * * device.Close(); */ }
internal static void CheckExchange(IInjectionDevice sender, ICaptureDevice receiver) { const int PacketsCount = 10; var packets = new List <RawCapture>(); var statuses = new List <CaptureStoppedEventStatus>(); void Receiver_OnPacketArrival(object s, PacketCapture e) { packets.Add(e.GetPacket()); } void Receiver_OnCaptureStopped(object s, CaptureStoppedEventStatus status) { statuses.Add(status); } // Configure sender sender.Open(); // Configure receiver receiver.Open(DeviceModes.Promiscuous); receiver.Filter = "ether proto 0x1234"; receiver.OnPacketArrival += Receiver_OnPacketArrival; receiver.OnCaptureStopped += Receiver_OnCaptureStopped; receiver.StartCapture(); // Send the packets var packet = EthernetPacket.RandomPacket(); packet.DestinationHardwareAddress = PhysicalAddress.Parse("FFFFFFFFFFFF"); packet.Type = (EthernetType)0x1234; for (var i = 0; i < PacketsCount; i++) { sender.SendPacket(packet); } // Wait for packets to arrive Thread.Sleep(2000); receiver.StopCapture(); // Checks Assert.That(packets, Has.Count.EqualTo(PacketsCount)); Assert.That(statuses, Has.Count.EqualTo(1)); Assert.AreEqual(statuses[0], CaptureStoppedEventStatus.CompletedWithoutError); }
static void Main(string[] args) { if (args == null) { throw new ArgumentNullException(nameof(args)); } //Liste der DashButtons definieren.MAC ohne Doppelpunkte dashlist.Add(PhysicalAddress.Parse("50F5DAEB018B")); //Seriennummer 114460 dashlist.Add(PhysicalAddress.Parse("AC63BE9D0BE7")); //Seriennummer 277109 dashlist.Add(PhysicalAddress.Parse("AC63BE3AC1CF")); //Seriennummer 832769 dashlist.Add(PhysicalAddress.Parse("AC63BE0EA91A")); //Seriennummer 823671 dashlist.Add(PhysicalAddress.Parse("50F5DA5B814D")); //Seriennummer 455294 dashlist.Add(PhysicalAddress.Parse("6C5697D41EA7")); //Seriennummer 772385 foreach (var macstring in dashlist) { DiclastEventTime.Add(macstring.ToString(), DateTime.Now.AddSeconds(-100)); } CaptureDeviceList devices = CaptureDeviceList.Instance; if (devices.Count < 1) { Console.WriteLine("Keine Netzwerkkarte gefunden."); return; } //Test für Timer einbauen. Timer holdOnLive = new Timer(); holdOnLive.Elapsed += HoldOnLive; holdOnLive.Interval = 3600000; holdOnLive.Enabled = true; //Initial das Web initialisieren. HoldOnLive(null, null); ICaptureDevice device = devices[DefaultInterfaceIndex]; device.OnPacketArrival += device_OnPacketArrival; device.Open(DeviceMode.Promiscuous, ReadTimeoutMilliseconds); device.StartCapture(); Console.WriteLine("-- Es wird auf Dashbuttons gelauscht..."); Console.ReadLine(); device.StopCapture(); device.Close(); }
public void Start() { var deviceList = CaptureDeviceList.Instance;// захват всех сетевых устройств GlobalDeviceClient = deviceList[0]; GlobalDeviceServer = deviceList[1]; proc.Start();// старт потока по обработке пакетов //// MAC1 -> MAC2 GlobalDeviceClient.OnPacketArrival += new PacketArrivalEventHandler(Program_OnPacketArrival10); GlobalDeviceClient.Open(); GlobalDeviceClient.StartCapture(); //// MAC2 -> MAC1 GlobalDeviceServer.OnPacketArrival += new PacketArrivalEventHandler(Program_OnPacketArrival10); GlobalDeviceServer.Open(); GlobalDeviceServer.StartCapture(); }
public void StartCapturing(int device_choice) { // If no devices were found print an error if(devices.Count < 1) { throw new Exception("No devices were found on this machine"); } device = devices[device_choice]; //Register our handler function to the 'packet arrival' event device.OnPacketArrival += new PacketArrivalEventHandler(device_OnPacketArrival); // Open the device for capturing device.Open(); // Start capture 'INFINTE' number of packets device.Capture(); }
//发送byte[]数据到当前活动网卡 private void sendPacket(byte[] bytes) { //选择一个网卡 ICaptureDevice device = getActiveNetAdapte(); device.Open(); try { // Send the packet out the network device device.SendPacket(bytes); } catch (Exception e) { log.writeLog("发送原始包出现异常:", log.msgType.error); } // Close the pcap device //device.Close(); }
public bool StartEquipment(ICaptureDevice device) { bool startSuccess = false; if (device!=null) { equipNetworkDevice = device; device.Open(DeviceMode.Promiscuous, ReadTimeOutMs); isWorking = true; device.Filter = this.filter; Thread thread = new Thread(new ParameterizedThreadStart(this.DoCapture)); thread.Start(device); } return startSuccess; }
/// <summary> /// IEnumerable helper allows for easy foreach usage, extension method and Linq usage /// </summary> /// <returns></returns> public static IEnumerable<RawCapture> GetSequence(ICaptureDevice dev, bool maskExceptions = true) { try { dev.Open(); while (true) { RawCapture packet = null; try { packet = dev.GetNextPacket(); } catch (PcapException pe) { if (!maskExceptions) throw pe; } if (packet == null) break; yield return packet; } } finally { dev.Close(); } }
/* Import a previous .pcap file */ private void Import() { OpenFileDialog openfile = new OpenFileDialog(); string path = ""; openfile.ShowDialog(); if (openfile.FileName != "") path = openfile.FileName; else return; try { device = new CaptureFileReaderDevice(path); device.Open(); } catch (System.Exception) { MessageBox.Show("Cannot import the file!"); return; } TotalPacket.Items.Clear(); RawCaptureList.Clear(); PacketCount = 0; device.OnPacketArrival += new PacketArrivalEventHandler(device_OnPacketArrival); device.Capture(); device.Close(); }
private int SendSynPacket(TcpPacket tcp) { tcp.SequenceNumber = 0; //A TCP Sync Packet will always have a destination address of 0 tcp.CWR = false; tcp.ECN = false; tcp.Urg = false; tcp.Ack = false; tcp.Psh = false; tcp.Rst = false; tcp.Syn = true; tcp.Fin = false; device = devices[1]; device.Open(DeviceMode.Promiscuous, 20); device.SendPacket(tcp); device.OnPacketArrival += new SharpPcap.PacketArrivalEventHandler(device_OnPacketArrival); //device.StartCapture(); RawCapture nexttcp = device.GetNextPacket(); //device.StopCapture(); if (nexttcp != null) { var packet = PacketDotNet.Packet.ParsePacket(nexttcp.LinkLayerType, nexttcp.Data); TcpPacket tcp1 = TcpPacket.GetEncapsulated(packet); if ((tcp1 != null) && (tcp1.Syn == true) && (tcp1.Ack == true)) { return 1; } else { return 0; } } else { return 0; } device.Close(); }
private void btnStartCapture_Click(object sender, RoutedEventArgs e) { // Extract a device from the list device = gbxDevInfo.DataContext as ICaptureDevice; // Register our handler function to the // 'packet arrival' event device.OnPacketArrival += new SharpPcap.PacketArrivalEventHandler(device_OnPacketArrival); // Open the device for capturing int readTimeoutMilliseconds = 1000; device.Open(DeviceMode.Promiscuous, readTimeoutMilliseconds); Console.WriteLine("-- Listening on {0}, hit 'Enter' to stop...", device.Description); // Start the capturing process device.StartCapture(); // Wait for 'Enter' from the user. Console.ReadLine(); }
/*private static void device_OnPcapStatistics(object sender, SharpPcap.WinPcap.StatisticsModeEventArgs e) { Console.WriteLine("bytes : {0}", e.Statistics.RecievedBytes); /*if (sender.Equals(rtChartPlotter.Form1.deviceMasterSent)) devicesPacketLengthS[0] += e.Statistics.RecievedBytes; else if (sender.Equals(deviceMasterRecv)) devicesPacketLengthR[0] += e.Statistics.RecievedBytes; if (sender.Equals(device1Sent)) devicesPacketLengthS[1] += e.Statistics.RecievedBytes; else if (sender.Equals(device1Recv)) devicesPacketLengthR[1] += e.Statistics.RecievedBytes; else if (sender.Equals(device2Sent)) devicesPacketLengthS[2] += e.Statistics.RecievedBytes; else if (sender.Equals(device2Recv)) devicesPacketLengthR[2] += e.Statistics.RecievedBytes; else if (sender.Equals(device3Sent)) devicesPacketLengthS[3] += e.Statistics.RecievedBytes; else if (sender.Equals(device3Recv)) devicesPacketLengthR[3] += e.Statistics.RecievedBytes; }*/ private void Form1_Load(object sender, EventArgs e) { lines = File.ReadAllLines(@"c:\dinjter.csv").Select(a => a.Split(',')); csv = from line in lines select (from piece in line select piece.Split(',')).ToArray(); textboxStream = new TextBoxStreamWriter(textBox1); Console.SetOut(textboxStream); // Volt meter stub. textBox10.Text = "0.00 V"; // Retrieve the device list devices = CaptureDeviceList.New(); // If no devices were found print an error if (devices.Count < 1) { Console.WriteLine("No devices were found on this machine"); return; } //set limit on NumericUpDown box this.numericUpDown1.Maximum = devices.Count-1; Console.WriteLine("The following devices are available on this machine:"); Console.WriteLine("----------------------------------------------------"); // Print out the available network devices foreach (ICaptureDevice dev in devices) Console.WriteLine("{0}\n", dev.ToString()); device = devices[2]; device.OnPacketArrival += new SharpPcap.PacketArrivalEventHandler(device_OnPacketArrival); device.Open(DeviceMode.Promiscuous, readTimeoutMilliseconds); device.StartCapture(); Console.WriteLine("device started"); // Assign selected device to each members deviceMasterSent = devices[deviceNumber]; device1Sent = devices[deviceNumber]; device2Sent = devices[deviceNumber]; device3Sent = devices[deviceNumber]; deviceMasterRecv = devices[deviceNumber]; device1Recv = devices[deviceNumber]; device2Recv = devices[deviceNumber]; device3Recv = devices[deviceNumber]; // Register our handler function to the // 'packet statistics' event deviceMasterSent.OnPacketArrival += new SharpPcap.PacketArrivalEventHandler(device_OnPacketArrival); deviceMasterRecv.OnPacketArrival += new SharpPcap.PacketArrivalEventHandler(device_OnPacketArrival); device1Sent.OnPacketArrival += new PacketArrivalEventHandler(device_OnPacketArrival); device1Recv.OnPacketArrival += new PacketArrivalEventHandler(device_OnPacketArrival); device2Sent.OnPacketArrival += new PacketArrivalEventHandler(device_OnPacketArrival); device2Recv.OnPacketArrival += new PacketArrivalEventHandler(device_OnPacketArrival); device3Sent.OnPacketArrival += new PacketArrivalEventHandler(device_OnPacketArrival); device3Recv.OnPacketArrival += new PacketArrivalEventHandler(device_OnPacketArrival); // Open the device for capturing deviceMasterSent.Open(DeviceMode.Promiscuous, readTimeoutMilliseconds); deviceMasterRecv.Open(DeviceMode.Promiscuous, readTimeoutMilliseconds); device1Sent.Open(DeviceMode.Promiscuous, readTimeoutMilliseconds); device1Recv.Open(DeviceMode.Promiscuous, readTimeoutMilliseconds); device2Sent.Open(DeviceMode.Promiscuous, readTimeoutMilliseconds); device2Recv.Open(DeviceMode.Promiscuous, readTimeoutMilliseconds); device3Sent.Open(DeviceMode.Promiscuous, readTimeoutMilliseconds); device3Recv.Open(DeviceMode.Promiscuous, readTimeoutMilliseconds); // Set device filter policy //deviceMasterSent.Filter = "src net 161.246.73.99"; //deviceMasterRecv.Filter = "dst net 161.246.73.99"; device1Sent.Filter = "src net 192.168.137.21"; device1Recv.Filter = "dst net 192.168.137.21"; device2Sent.Filter = "src net 192.168.137.22"; device2Recv.Filter = "dst net 192.168.137.22"; device3Sent.Filter = "src net 192.168.137.23"; device3Recv.Filter = "dst net 192.168.137.23"; Console.WriteLine("-- Listening on {0}, [Initial listening device]", deviceMasterSent.Description); // Start the capturing process deviceMasterSent.StartCapture(); deviceMasterRecv.StartCapture(); device1Sent.StartCapture(); device1Recv.StartCapture(); device2Sent.StartCapture(); device2Recv.StartCapture(); device3Sent.StartCapture(); device3Recv.StartCapture(); //isDeviceOpen = true; }
private void Form1_Load(object sender, EventArgs e) { timeDelay = timer1.Interval; lines = File.ReadAllLines(@"c:\dinjter.csv").Select(a => a.Split(',')); csv = from line in lines select (from piece in line select piece.Split(',')).ToArray(); textboxStream = new TextBoxStreamWriter(textBox1); Console.SetOut(textboxStream); // Volt meter stub. textBox10.Text = "0.00 V"; // Retrieve the device list devices = CaptureDeviceList.New(); // If no devices were found print an error if (devices.Count < 1) { Console.WriteLine("No devices were found on this machine"); return; } //set limit on NumericUpDown box this.numericUpDown1.Maximum = devices.Count - 1; Console.WriteLine("The following devices are available on this machine:"); Console.WriteLine("----------------------------------------------------"); // Print out the available network devices foreach (ICaptureDevice dev in devices) Console.WriteLine("{0}\n", dev.ToString()); device0s = devices[0]; device0r = devices[0]; device1s = devices[0]; device1r = devices[0]; device2s = devices[0]; device2r = devices[0]; device3s = devices[0]; device3r = devices[0]; device0s.OnPacketArrival += new SharpPcap.PacketArrivalEventHandler(device_OnPacketArrival); device1s.OnPacketArrival += new SharpPcap.PacketArrivalEventHandler(device_OnPacketArrival); device1r.OnPacketArrival += new SharpPcap.PacketArrivalEventHandler(device_OnPacketArrival); device2s.OnPacketArrival += new SharpPcap.PacketArrivalEventHandler(device_OnPacketArrival); device2r.OnPacketArrival += new SharpPcap.PacketArrivalEventHandler(device_OnPacketArrival); device3s.OnPacketArrival += new SharpPcap.PacketArrivalEventHandler(device_OnPacketArrival); device3r.OnPacketArrival += new SharpPcap.PacketArrivalEventHandler(device_OnPacketArrival); device0s.Open(DeviceMode.Promiscuous, readTimeoutMilliseconds); device1s.Open(DeviceMode.Promiscuous, readTimeoutMilliseconds); device1r.Open(DeviceMode.Promiscuous, readTimeoutMilliseconds); device2s.Open(DeviceMode.Promiscuous, readTimeoutMilliseconds); device2r.Open(DeviceMode.Promiscuous, readTimeoutMilliseconds); device3s.Open(DeviceMode.Promiscuous, readTimeoutMilliseconds); device3r.Open(DeviceMode.Promiscuous, readTimeoutMilliseconds); device0s.StartCapture(); //device1s.StartCapture(); //device1r.StartCapture(); //device2s.StartCapture(); //device2r.StartCapture(); //device3s.StartCapture(); //device3r.StartCapture(); Console.WriteLine("device started"); }
public void StartCapture(string deviceName, string ip) { if (deviceName == "" || ip == "") { throw new Exception("Device Input Fail"); } //Get our index back. (0) blabla int index = Convert.ToInt32(deviceName.Split(')')[0].Replace("(", "")); if (WinPcapDeviceList.Instance.Count <= index) { throw new Exception("Device Fail"); } device = WinPcapDeviceList.Instance[index]; // Register our handler function to the // 'packet arrival' event device.OnPacketArrival += device_OnPacketArrival; // Open the device for capturing int readTimeoutMilliseconds = 1000; device.Open(DeviceMode.Promiscuous, readTimeoutMilliseconds); //Filter string filter = "host " + ip; device.Filter = filter; captureIp = ip; // Start the capturing process device.StartCapture(); }
private void button1_Click(object sender, EventArgs e) { if (this.comboBox1.SelectedIndex >= 0) { try { //Register our handler function to the 'packet arrival' event _device = devices[this.comboBox1.SelectedIndex]; _device.OnPacketArrival += new PacketArrivalEventHandler(device_OnPacketArrival); _device.Open(); _device.Filter = textBox1.Text; for (int i = 0; i <= 5; i++) PacketQueue[i].Clear(); _device.StartCapture(); try { if (_Backgroundthread.IsAlive) { _Backgroundthread.Abort(); } } catch { } ThreadStart threadstart = new ThreadStart(Backgroundprocess); _Backgroundthread = new Thread(threadstart); _Backgroundthread.Start(); //开启后台线程 textBox1.ReadOnly = true; button2.Enabled = true; button1.Enabled = false; } catch (Exception ex) { MessageBox.Show("过滤规则错误!"+ex.Message,"警告!"); } } else MessageBox.Show("请选择网卡!","提示"); }
public void UpdateDevInfo(ICaptureDevice dev) { // if we are sending packet to all adapters if (dev == null) { if (sIP == null) { sIP = IPAddress.Parse("255.255.255.255"); Console.WriteLine("Set sIP to: " + sIP.ToString()); } if (dIP == null) { dIP = IPAddress.Parse("255.255.255.255"); Console.WriteLine("Set dIP to: " + dIP.ToString()); } if (sMAC == null) { sMAC = PhysicalAddress.Parse("FF-FF-FF-FF-FF-FF"); Console.WriteLine("Set sMAC to: " + sMAC.ToString()); } if (dMAC == null) { dMAC = PhysicalAddress.Parse("FF-FF-FF-FF-FF-FF"); Console.WriteLine("Set dMAC to: " + dMAC.ToString()); } } // if we picked an actual adapter else { dev.Open(); // if source address is not defined, fill out the sIP List<IPAddress> ipAddresses = Utility.GetIPAddress(dev); foreach (IPAddress add in ipAddresses) { if (sIP == null && dIP != null) { if (dIP.ToString().Contains(".") && add.ToString().Contains(".")) { sIP = add; Console.WriteLine("Set sIP to: " + add.ToString()); } else if (dIP.ToString().Contains(":") && add.ToString().Contains(":")) { sIP = add; Console.WriteLine("Set sIP to: " + add.ToString()); } } } if (sIP == null) { Console.WriteLine("The chosen adapter did not have a valid address"); Environment.Exit(1); } //fill out source mac if it is null if (sMAC == null) { sMAC = dev.MacAddress; Console.WriteLine("Set sMAC to: " + sMAC.ToString()); } if (dMAC == null) { dMAC = PhysicalAddress.Parse("FF-FF-FF-FF-FF-FF"); Console.WriteLine("Set dMAC to: " + dMAC.ToString()); } dev.Close(); } }
private void StartCapture(int itemIndex) { device = CaptureDeviceList.Instance[itemIndex]; // start the background thread BackgroundThreadStop = false; backgroundThread = new System.Threading.Thread(BackgroundThread); backgroundThread.Start(); // setup background capture arrivalEventHandler = new PacketArrivalEventHandler(device_OnPacketArrival); device.OnPacketArrival += arrivalEventHandler; device.Open(); if (filter!=null) device.Filter = filter; // start the background capture device.StartCapture(); timer1.Start(); }
/// <summary> /// Capturedevice the packet form specific /// </summary> /// <param name="timeout"></param> /// <param name="device"></param> public void Start(int timeout, ICaptureDevice device) { device.OnPacketArrival += new SharpPcap.PacketArrivalEventHandler(OnPacketArrival); device.Open(DeviceMode.Promiscuous, timeout); device.StartCapture(); }
private bool _StartCapture() { // if capturing is already started, just return true if (null != _curNIC) { return true; } int nSelectedNIC = OConfiguration.instanceOf().GetSelectedNIC(); if (nSelectedNIC < 0) { MessageBox.Show("There is no device selected.", "Error"); return false; } if (nSelectedNIC >= CaptureDeviceList.Instance.Count) { MessageBox.Show("The selected device is not valid. Select device again", "Error"); return false; } // clear all packet before starting capture _capturedPackets.Clear(); // clear all current packet list _curPacketList.Clear(); // clear ui lstPackets.Items.Clear(); hexEdit.ByteProvider = null; _curNIC = CaptureDeviceList.Instance[nSelectedNIC]; _threadObject = new Thread(_ThreadProc); _threadObject.Start(); // Set up capture _eventPacketArrival = new PacketArrivalEventHandler(_OnPacketArrival); ; _eventCaptureStopped = new CaptureStoppedEventHandler(_OnCaptureStopped); _curNIC.OnPacketArrival += _eventPacketArrival; _curNIC.OnCaptureStopped += _eventCaptureStopped; _curNIC.Open(); // start capture _curNIC.StartCapture(); return true; }
private void StartCapture(int itemIndex) { packetCount = 0; device = CaptureDeviceList.Instance[itemIndex]; packetStrings = new Queue<PacketWrapper>(); bs = new BindingSource(); dataGridView.DataSource = bs; LastStatisticsOutput = DateTime.Now; // start the background thread BackgroundThreadStop = false; backgroundThread = new System.Threading.Thread(BackgroundThread); backgroundThread.Start(); // setup background capture arrivalEventHandler = new PacketArrivalEventHandler(device_OnPacketArrival); device.OnPacketArrival += arrivalEventHandler; captureStoppedEventHandler = new CaptureStoppedEventHandler(device_OnCaptureStopped); device.OnCaptureStopped += captureStoppedEventHandler; device.Open(); // force an initial statistics update captureStatistics = device.Statistics; UpdateCaptureStatistics(); // start the background capture device.StartCapture(); // disable the stop icon since the capture has stopped startStopToolStripButton.Image = global::WinformsExample.Properties.Resources.stop_icon_enabled; startStopToolStripButton.ToolTipText = "Stop capture"; }
private void button1_Click(object sender, EventArgs e) { device0s.StopCapture(); device0s.Close(); //isDeviceOpen = false; device0s = devices[deviceNumber]; device0s = devices[deviceNumber]; Console.WriteLine("-- Listening on {0}", device0s.Description); // Register our handler function to the // 'packet arrival' event device0s.OnPacketArrival += new PacketArrivalEventHandler(device_OnPacketArrival); // Open the device for capturing device0s.Open(DeviceMode.Promiscuous, readTimeoutMilliseconds); device0s.StartCapture(); //isDeviceOpen = true; }
private void button1_Click(object sender, EventArgs e) { deviceMasterSent.StopCapture(); deviceMasterSent.Close(); deviceMasterRecv.StopCapture(); deviceMasterRecv.Close(); device1Sent.StopCapture(); device1Sent.Close(); device2Sent.StopCapture(); device2Sent.Close(); device3Sent.StopCapture(); device3Sent.Close(); //isDeviceOpen = false; deviceMasterSent = devices[deviceNumber]; deviceMasterRecv = devices[deviceNumber]; device1Sent = devices[deviceNumber]; device1Recv = devices[deviceNumber]; device2Sent = devices[deviceNumber]; device2Recv = devices[deviceNumber]; device3Sent = devices[deviceNumber]; device3Recv = devices[deviceNumber]; Console.WriteLine("-- Listening on {0}", deviceMasterSent.Description); // Register our handler function to the // 'packet arrival' event deviceMasterSent.OnPacketArrival += new PacketArrivalEventHandler(device_OnPacketArrival); deviceMasterRecv.OnPacketArrival += new PacketArrivalEventHandler(device_OnPacketArrival); device1Sent.OnPacketArrival += new PacketArrivalEventHandler(device_OnPacketArrival); device1Recv.OnPacketArrival += new PacketArrivalEventHandler(device_OnPacketArrival); device2Sent.OnPacketArrival += new PacketArrivalEventHandler(device_OnPacketArrival); device2Recv.OnPacketArrival += new PacketArrivalEventHandler(device_OnPacketArrival); device3Sent.OnPacketArrival += new PacketArrivalEventHandler(device_OnPacketArrival); device3Recv.OnPacketArrival += new PacketArrivalEventHandler(device_OnPacketArrival); // Open the device for capturing deviceMasterSent.Open(DeviceMode.Promiscuous, readTimeoutMilliseconds); deviceMasterRecv.Open(DeviceMode.Promiscuous, readTimeoutMilliseconds); device1Sent.Open(DeviceMode.Promiscuous, readTimeoutMilliseconds); device1Recv.Open(DeviceMode.Promiscuous, readTimeoutMilliseconds); device2Sent.Open(DeviceMode.Promiscuous, readTimeoutMilliseconds); device2Recv.Open(DeviceMode.Promiscuous, readTimeoutMilliseconds); device3Sent.Open(DeviceMode.Promiscuous, readTimeoutMilliseconds); device3Recv.Open(DeviceMode.Promiscuous, readTimeoutMilliseconds); /*// Set device to statistics mode deviceMasterSent.Mode = CaptureMode.Statistics; deviceMasterRecv.Mode = CaptureMode.Statistics; device1Sent.Mode = CaptureMode.Statistics; device1Recv.Mode = CaptureMode.Statistics; device2Sent.Mode = CaptureMode.Statistics; device2Recv.Mode = CaptureMode.Statistics; device3Sent.Mode = CaptureMode.Statistics; device3Recv.Mode = CaptureMode.Statistics;*/ // Set device filter policy //deviceMasterSent.Filter = "src net 161.246.73.99"; //deviceMasterRecv.Filter = "dst net 161.246.73.99"; device1Sent.Filter = "src net 192.168.137.21"; device1Recv.Filter = "dst net 192.168.137.21"; device2Sent.Filter = "src net 192.168.137.22"; device2Recv.Filter = "dst net 192.168.137.22"; device3Sent.Filter = "src net 192.168.137.23"; device3Recv.Filter = "dst net 192.168.137.23"; deviceMasterSent.StartCapture(); deviceMasterRecv.StartCapture(); device1Sent.StartCapture(); device1Recv.StartCapture(); device2Sent.StartCapture(); device2Recv.StartCapture(); device3Sent.StartCapture(); //isDeviceOpen = true; }
private void btnSendPacket_Click(object sender, RoutedEventArgs e) { device = gbxDevInfo.DataContext as ICaptureDevice; // Open the device device.Open(); try { IPAddress ip = IPAddress.Parse(tbxSourceIp.Text); IPAddress ipaddress = System.Net.IPAddress.Parse(tbxDestinationIp.Text); TcpPacket tcpPakje = new TcpPacket(80, 80); IPv4Packet pakje = new IPv4Packet(ip, ipaddress); pakje.PayloadData = System.Text.Encoding.ASCII.GetBytes(tbxPayloadIp.Text); pakje.TimeToLive = int.Parse(tbxTTLIp.Text); // pakje.Protocol = tbxProtocolIp.Text; device.SendPacket(pakje); Console.WriteLine("-- Packet sent successfuly."); } catch (Exception ex) { Console.WriteLine("-- " + ex.Message); } // Close the pcap device device.Close(); Console.WriteLine("-- Device closed."); }