private void mFileCaptureMenu_Click(object pSender, EventArgs pArgs) { if (mCaptureDevice != null) { mCaptureDevice.Close(); mCaptureDevice = null; return; } SetupForm frmSetup = new SetupForm(); if (frmSetup.ShowDialog(this) != DialogResult.OK) { return; } foreach (PcapDevice device in new PcapDeviceList()) { if (device.Interface.FriendlyName == Config.Instance.Interface) { mCaptureDevice = device; break; } } mCaptureDevice.Open(true, 1); mCaptureDevice.SetFilter(string.Format("tcp portrange {0}-{1}", Config.Instance.LowPort, Config.Instance.HighPort)); }
private void StartCapture() { if (!capturedPacketsHaveBeenSaved) { DialogResult userWish = ShowDialogAskingUserToSaveCaptureData(ActionType.StartingNewCapture); if (userWish == DialogResult.OK) { SaveCapturedPacketsToFile(); } else if (userWish == DialogResult.Cancel) { return; } } // Nullify the packets counter and clear the structures that keep // the captured packets info ClearDataStructures(); try { Cursor = Cursors.WaitCursor; // Open the device for capturing device.Open(true, 1000); // tcpdump filter to capture only TCP/IP packets device.SetFilter(toolStripComboBoxFilters.Text); // Register our handler function to the "packet arrival" event device.OnPacketArrival += new Pcap.PacketArrivalEvent(device_OnPacketArrival); // Start the capturing process device.StartCapture(); // Enable the navigation buttons SetNavigationButtonsEnabledState(true); // Set the MainForm text SetMainFormText(String.Format("{0}: Capturing - Traffic Dissector", device.Description)); // Set the status labels texts SetStatusLabelsTexts("Live capture in progress", "|No packets"); SetMenuItemsEnabledState(false); } catch (Exception ex) { MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); device.Close(); } finally { Cursor = Cursors.Default; } }
private void MainForm_FormClosed(object pSender, FormClosedEventArgs pArgs) { mTimer.Enabled = false; if (mDevice != null) { mDevice.Close(); } mClosed = true; }
// Disposer public void Dispose() { if (trackdevice != null) { // Stop capturing packets try { trackdevice.StopCapture(); } catch (Exception) { }; try { trackdevice.Close(); } catch (Exception) { }; trackdevice = null; } }
private void buttonInject_Click(object sender, EventArgs e) { bool isEthernetHeaderCorrect = ethernetHeaderUserControl.ValidateUserInput(); bool isIPv4HeaderCorrect = iPv4HeaderUserControl.ValidateUserInput(); bool isTcpHeaderCorrect = tcpHeaderUserControl.ValidateUserInput(); bool isDeviceChosen = chooseDeviceUserControl.ValidateChosenDevice(); if (!isEthernetHeaderCorrect || !isIPv4HeaderCorrect || !isTcpHeaderCorrect || !isDeviceChosen) { return; } EthernetPacket ethernetHeader = ethernetHeaderUserControl.CreateEthernetPacket(0); IPv4Packet ipv4Packet = iPv4HeaderUserControl.CreateIPv4Packet(ethernetHeader); TCPPacket tcpPacket = tcpHeaderUserControl.CreateTcpPacket(ipv4Packet); PcapDevice device = chooseDeviceUserControl.Device; bool isDeviceOpenedInThisForm = false; try { if (!device.Opened) { device.Open(); isDeviceOpenedInThisForm = true; } // Send the packet out the network device device.SendPacket(tcpPacket); } catch (Exception ex) { MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } finally { if (isDeviceOpenedInThisForm) { device.Close(); } } }
public void Stop() { if (IsActive == false) { return; } try { _device.Close(); } catch { } IsActive = false; }
private void buttonInject_Click(object sender, EventArgs e) { bool isEthernetHeaderCorrect = ethernetHeaderUserControl.ValidateUserInput(); bool isPacketLengthValid = ValidatePacketLength(); bool isDeviceChosen = chooseDeviceUserControl.ValidateChosenDevice(); if (!isEthernetHeaderCorrect || !isPacketLengthValid || !isDeviceChosen) { return; } int payloadLength = packetLength - EthernetFields_Fields.ETH_HEADER_LEN; // Create an Ethernet packet. EthernetPacket ethernetPacket = ethernetHeaderUserControl.CreateEthernetPacket(payloadLength); PcapDevice device = chooseDeviceUserControl.Device; bool isDeviceOpenedInThisForm = false; try { if (!device.Opened) { device.Open(); isDeviceOpenedInThisForm = true; } // Send the packet out the network device device.SendPacket(ethernetPacket); } catch (Exception ex) { MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } finally { if (isDeviceOpenedInThisForm) { device.Close(); } } }
private void StopCapture(object state) { PcapDevice device = (PcapDevice)state; device.StopCaptureTimeout = new TimeSpan(0, 0, 0, 0, 500); try { device.StopCapture(); } catch { Log.Warn("Terminals needed more than 500 milliseconds to abort the PCap thread."); } device.Close(); }
public static void Run(string[] args) { int lLen = EthernetFields_Fields.ETH_HEADER_LEN; const int MIN_PKT_LEN = 42; byte[] data = System.Text.Encoding.ASCII.GetBytes("HELLO"); byte[] bytes = new byte[MIN_PKT_LEN + data.Length]; Array.Copy(data, 0, bytes, MIN_PKT_LEN, data.Length); List <PcapDevice> devices = Pcap.GetAllDevices(); PcapDevice device = devices[2]; UDPPacket packet = new UDPPacket(lLen, bytes); //Ethernet Fields packet.DestinationHwAddress = PhysicalAddress.Parse("001122334455"); // NOTE: the source hw address will be filled in by the network stack or the // network hardware // packet.SourceHwAddress = device.MacAddress; packet.EthernetProtocol = EthernetPacket.EtherType.IP; //IP Fields packet.DestinationAddress = System.Net.IPAddress.Parse("58.100.187.167"); // NOTE: the source address will be filled in by the network stack based on // the device used for sending // packet.SourceAddress = System.Net.IPAddress.Parse(device.IpAddress); packet.IPProtocol = IPProtocol.IPProtocolType.UDP; packet.TimeToLive = 20; packet.ipv4.Id = 100; packet.IPVersion = IPPacket.IPVersions.IPv4; packet.ipv4.IPTotalLength = bytes.Length - lLen; packet.ipv4.IPHeaderLength = IPv4Fields_Fields.IP_HEADER_LEN; //UDP Fields packet.DestinationPort = 9898; packet.SourcePort = 80; //TODO: checksum methods are disabled due to unfinished ipv4/ipv6 work throw new System.NotImplementedException(); // packet.ComputeIPChecksum(); // packet.ComputeUDPChecksum(); device.Open(); device.SendPacket(packet); device.Close(); }
private void SetupAdapter() { if (device != null) { device.StopCapture(); device.Close(); } foreach (LibPcapLiveDevice pcapDevice in LibPcapLiveDeviceList.Instance) { if (pcapDevice.Interface.Name == Config.Instance.Interface) { device = pcapDevice; break; } } if (device == null) { // Well shit... const string message = "Invalid configuration. Please re-setup your MapleShark configuration."; MessageBox.Show(message, "MapleShark2", MessageBoxButtons.OK, MessageBoxIcon.Error); if (ShowSetupForm() != DialogResult.OK) { Close(); return; } SetupAdapter(); } try { device.Open(DeviceMode.Promiscuous, 10); } catch { MessageBox.Show("Failed to set the device in Promiscuous mode! But that doesn't really matter lol."); device.Open(); } device.OnPacketArrival += device_OnPacketArrival; device.Filter = $"tcp portrange {Config.Instance.LowPort}-{Config.Instance.HighPort}"; device.StartCapture(); }
public async Task StartCapturing() { _stopped = false; await Task.Run(() => { _device = _dependencies.GetActualDevice(_configuration.InterfaceFriendlyName); _device?.Open(DeviceMode.Promiscuous, 1000); while (!_stopped) { try { RawCapture rawPacket = _device.GetNextPacket(); if (rawPacket != null) { PacketCaptured?.Invoke(this, rawPacket); } } catch (Exception e) { //try refresh device if something has changed in pc settings var refreshedDevice = _dependencies.GetActualDevice(_configuration.InterfaceFriendlyName); if (refreshedDevice != null) { _device = refreshedDevice; _device.Open(DeviceMode.Promiscuous, 1000); } ErrorOccured?.Invoke(this, e); KaTaLyzerLogger.Log(LogLevel.Error, e, new KeyValuePair <string, object>("Adapter", this)).Wait(); } } _device?.Close(); }); }
private void SendCaptureFile() { if (!ValidateUserInput()) { return; } // Get the network device through which the packets will be sent. PcapDevice device = chooseDeviceUserControl.Device; // Get an offline file pcap device PcapDevice offlineDevice = new PcapOfflineDevice(textBoxCaptureFile.Text); PcapSendQueue sendQueue = null; bool isDeviceOpenedInThisForm = false; try { Cursor = Cursors.WaitCursor; if (!device.Opened) { device.Open(); isDeviceOpenedInThisForm = true; } // Open the device for capturing offlineDevice.Open(); // Allocate a new send queue sendQueue = new PcapSendQueue ((int)((PcapOfflineDevice)offlineDevice).FileSize); Packet packet; // Go through all packets in the file and add to the queue while ((packet = offlineDevice.GetNextPacket()) != null) { if (!sendQueue.Add(packet)) { MessageBox.Show( "Packet buffer too small, not all the packets will be sent.", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning); break; } } if (device.PcapDataLink != offlineDevice.PcapDataLink) { DialogResult answer = MessageBox.Show( "The datalink of the capture differs from the one of the" + "\nselected interface. Do you want to continue?", "Question", MessageBoxButtons.YesNo, MessageBoxIcon.Question); if (answer == DialogResult.No) { return; } } int bytesSent = device.SendQueue(sendQueue, false); if (bytesSent < sendQueue.CurrentLength) { MessageBox.Show( String.Format("An error occurred sending the packets: {0}.\nOnly {1} bytes were sent.", device.LastError, bytesSent), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } } catch (Exception ex) { MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } finally { // Close the pcap device offlineDevice.Close(); // Free the queue if (sendQueue != null) { sendQueue.Dispose(); } if (isDeviceOpenedInThisForm) { device.Close(); } Cursor = Cursors.Default; } }
static void Main(string[] args) { string ver = SharpPcap.Version.VersionString; /* Print SharpPcap version */ Console.WriteLine("SharpPcap {0}, Example12.PacketManipulation.cs", ver); Console.WriteLine(); /* Retrieve the device list */ List <PcapDevice> devices = SharpPcap.Pcap.GetAllDevices(); /*If no device exists, print error */ if (devices.Count < 1) { Console.WriteLine("No device found on this machine"); return; } Console.WriteLine("The following devices are available on this machine:"); Console.WriteLine("----------------------------------------------------"); Console.WriteLine(); int i = 0; /* Scan the list printing every entry */ foreach (PcapDevice dev in devices) { /* Description */ Console.WriteLine("{0}) {1}", i, dev.Description); i++; } Console.WriteLine("{0}) {1}", i, "Read packets from offline pcap file"); Console.WriteLine(); Console.Write("-- Please choose a device to capture: "); int choice = int.Parse(Console.ReadLine()); PcapDevice device = null; if (choice == i) { Console.Write("-- Please enter an input capture file name: "); string capFile = Console.ReadLine(); device = SharpPcap.Pcap.GetPcapOfflineDevice(capFile); } else { device = devices[choice]; } //Register our handler function to the 'packet arrival' event device.OnPacketArrival += new SharpPcap.Pcap.PacketArrivalEvent(device_PcapOnPacketArrival); //Open the device for capturing //true -- means promiscuous mode //1000 -- means a read wait of 1000ms device.Open(true, 1000); Console.WriteLine(); Console.WriteLine ("-- Listenning on {0}, hit 'Ctrl-C' to exit...", device.Description); //Start capture 'INFINTE' number of packets device.Capture(SharpPcap.Pcap.INFINITE); //Close the pcap device //(Note: this line will never be called since // we're capturing infinite number of packets device.Close(); }
public static void Main(string[] args) { string ver = SharpPcap.Version.VersionString; /* Print SharpPcap version */ Console.WriteLine("SharpPcap {0}, Example11.Statistics.cs", ver); /* Retrieve the device list */ List <PcapDevice> devices = SharpPcap.Pcap.GetAllDevices(); /*If no device exists, print error */ if (devices.Count < 1) { Console.WriteLine("No device found on this machine"); return; } Console.WriteLine(); Console.WriteLine("The following devices are available on this machine:"); Console.WriteLine("----------------------------------------------------"); Console.WriteLine(); int i = 0; /* Scan the list printing every entry */ foreach (PcapDevice dev in devices) { /* Description */ Console.WriteLine("{0}) {1} {2}", i, dev.Name, dev.Description); i++; } Console.WriteLine(); Console.Write("-- Please choose a device to gather statistics on: "); i = int.Parse(Console.ReadLine()); PcapDevice device = devices[i]; //Register our handler function to the 'pcap statistics' event device.OnPcapStatistics += new Pcap.PcapStatisticsEvent(device_PcapOnPcapStatistics); //Open the device for capturing //true -- means promiscuous mode //1000 -- means stats will be collected 1000ms device.Open(true, 1000); //Handle TCP packets only device.SetFilter("tcp"); //Set device to statistics mode device.Mode = PcapDevice.PcapMode.Statistics; Console.WriteLine(); Console.WriteLine("-- Gathering statistics on \"{0}\", hit 'Enter' to stop...", device.Description); //Start the capturing process device.StartCapture(); //Wait for 'Enter' from the user. Console.ReadLine(); //Stop the capturing process device.StopCapture(); //Close the pcap device device.Close(); Console.WriteLine("Capture stopped, device closed."); Console.Write("Hit 'Enter' to exit..."); Console.ReadLine(); }
public bool connect(IPEndPoint ipEnd, int port) { int lLen = EthernetFields_Fields.ETH_HEADER_LEN; //SYN packet creation #region Various Initializations ARP arper = new ARP(); var bytes = new byte[54]; var tcp = new TCPPacket(lLen, bytes, true) { IPVersion = IPPacket.IPVersions.IPv4 }; #endregion #region Ethernet Fields tcp.SourceHwAddress = _dev.Interface.MacAddress; arper.DeviceName = _dev.Name; arper.LocalIP = _dev.Interface.Addresses[1].Addr.ipAddress; arper.LocalMAC = _dev.Interface.MacAddress; //MAC address of gateway is provided by arp protocol tcp.DestinationHwAddress = arper.Resolve(_gatewayAddr, _dev.Name); tcp.EthernetProtocol = EthernetPacket.EtherType.IP; #endregion #region IP Fields tcp.DestinationAddress = ipEnd.Address; tcp.SourceAddress = _dev.Interface.Addresses[1].Addr.ipAddress; tcp.IPProtocol = IPProtocol.IPProtocolType.TCP; tcp.TimeToLive = 20; tcp.ipv4.Id = 100; tcp.ipv4.IPTotalLength = bytes.Length - lLen; tcp.ipv4.IPHeaderLength = IPv4Fields_Fields.IP_HEADER_LEN; #endregion #region TCP Fields tcp.SourcePort = 2222; tcp.DestinationPort = port; tcp.Syn = true; tcp.WindowSize = 555; tcp.SequenceNumber = 0; tcp.TCPHeaderLength = TCPFields_Fields.TCP_HEADER_LEN; #endregion //Headers checksum calculations tcp.ipv4.ComputeIPChecksum(); tcp.ComputeTCPChecksum(); _dev.Open(false, 20); _dev.SetFilter("ip src " + tcp.DestinationAddress + " and tcp src port " + tcp.DestinationPort + " and tcp dst port " + tcp.SourcePort); //Send the packet Console.Write("Sending SYN packet: " + tcp + "..."); _dev.SendPacket(tcp); Console.WriteLine("SYN Packet sent."); TCPPacket reply = null; var watch = new Stopwatch(); bool received = false; watch.Start(); //Condition including timeout check. while (watch.ElapsedMilliseconds < _timeout && received != true) { if ((reply = (TCPPacket)_dev.GetNextPacket()) != null) { Console.WriteLine("SYN ACK Reply received: " + reply); received = true; } } //A reply hasn't returned if (!received) { _dev.Close(); throw new Exception("TIME_OUT"); } //Remote host reported closed connection if (reply.Rst) { _dev.Close(); throw new Exception("CLOSED"); } //Remote host reported opened connection if (reply.Ack) { tcp.Syn = false; tcp.Rst = true; tcp.WindowSize = 0; tcp.ipv4.ComputeIPChecksum(); tcp.ComputeTCPChecksum(); Console.Write("Sending RST packet: " + tcp + "..."); _dev.SendPacket(tcp); Console.WriteLine("RST Packet sent."); _dev.Close(); } return(true); }
/// <summary> /// Resolves the MAC address of the specified IP address /// </summary> /// <param name="destIP">The IP address to resolve</param> /// <param name="deviceName">The local network device name on which to send the ARP request</param> /// <returns>The MAC address that matches to the given IP address</returns> public PhysicalAddress Resolve(System.Net.IPAddress destIP, string deviceName) { PhysicalAddress localMAC = LocalMAC; System.Net.IPAddress localIP = LocalIP; //NetworkDevice device = new NetworkDevice(DeviceName); PcapDevice device = Pcap.GetPcapDevice(DeviceName); //FIXME: PcapDevices don't have IpAddress // These were present under Windows specific network adapters // and may be present in pcap in the future with pcap-ng // if no local ip address is specified use the one from the // local device #if false if (localIP == null) { localIP = device.IpAddress; } #endif // if no local mac address is specified use the one from the device if (LocalMAC == null) { localMAC = device.Interface.MacAddress; } //Build a new ARP request packet ARPPacket request = BuildRequest(destIP, localMAC, localIP); //create a "tcpdump" filter for allowing only arp replies to be read String arpFilter = "arp and ether dst " + localMAC.ToString(); //open the device with 20ms timeout device.Open(true, 20); //set the filter device.SetFilter(arpFilter); //inject the packet to the wire device.SendPacket(request); ARPPacket reply; while (true) { //read the next packet from the network reply = (ARPPacket)device.GetNextPacket(); if (reply == null) { continue; } //if this is the reply we're looking for, stop if (reply.ARPSenderProtoAddress.Equals(destIP)) { break; } } //free the device device.Close(); //return the resolved MAC address return(reply.ARPSenderHwAddress); }
public static void SendTcpSyn(PcapDevice dev) { byte[] bytes = new byte[54]; TCPPacket tcp = new TCPPacket(lLen, bytes, true); //Ethernet fields // tcp.SourceHwAddress = dev.MacAddress; //Set the source mac of the local device tcp.DestinationHwAddress = PhysicalAddress.Parse(destMAC); //Set the dest MAC of the gateway tcp.EthernetProtocol = EthernetPacket.EtherType.IP; //IP fields tcp.DestinationAddress = destIP; //The IP of the destination host // tcp.SourceAddress = System.Net.IPAddress.Parse(dev.IpAddress); //The IP of the local device tcp.IPProtocol = IPProtocol.IPProtocolType.TCP; tcp.TimeToLive = 20; tcp.ipv4.Id = 100; tcp.IPVersion = IPPacket.IPVersions.IPv4; tcp.ipv4.IPTotalLength = bytes.Length - lLen; //Set the correct IP length tcp.ipv4.IPHeaderLength = IPv4Fields_Fields.IP_HEADER_LEN; //TCP fields tcp.SourcePort = sourcePort; //The TCP source port tcp.DestinationPort = destPort; //The TCP dest port tcp.Syn = true; //Set the SYN flag on tcp.WindowSize = 555; tcp.AcknowledgmentNumber = 1000; tcp.SequenceNumber = 1000; tcp.TCPHeaderLength = TCPFields_Fields.TCP_HEADER_LEN; //Set the correct TCP header length //tcp.SetData( System.Text.Encoding.ASCII.GetBytes("HELLO") ); //Calculate checksums //TODO: need to implement the checksumming routines throw new System.NotImplementedException(); // tcp.ComputeIPChecksum(); // tcp.ComputeTCPChecksum(); dev.Open(true, 20); //Set a filter to capture only replies //FIXME: PcapDevice doesn't have an IpAddress. Not sure if the more permissive // filter will work the same // dev.PcapSetFilter("ip src "+destIP+" and ip dst "+ // dev.IpAddress+" and tcp src port "+destPort+" and tcp dst port "+sourcePort); dev.SetFilter("ip src " + destIP + " and tcp src port " + destPort + " and tcp dst port " + sourcePort); //Send the packet Console.Write("Sending packet: " + tcp + "..."); dev.SendPacket(tcp); Console.WriteLine("Packet sent."); //Holds the reply Packet reply; //Wait till you get a reply while ((reply = dev.GetNextPacket()) == null) { ; } //print the reply Console.WriteLine("Reply received: " + reply); dev.Close(); }
public ScanMessage Connect(IPEndPoint ipEndPoint) { // SYN packet creation //MAC address of gateway is provided by arp protocol ARP arper = new ARP(device.Name); arper.LocalIP = device.Interface.Addresses[0].Addr.ipAddress; arper.LocalMAC = device.Interface.MacAddress; PhysicalAddress gatewayHwAddress = arper.Resolve(gatewayAddress); EthernetPacket ethernetHeader = new EthernetPacket( device.Interface.MacAddress, gatewayHwAddress, EthernetPacketType.IPv4, null); byte[] content = new byte[ EthernetFields_Fields.ETH_HEADER_LEN + IPv4Fields_Fields.IP_HEADER_LEN + TCPFields_Fields.TCP_HEADER_LEN]; IPv4Packet ipv4Packet = new IPv4Packet( EthernetFields_Fields.ETH_HEADER_LEN, content); // Ethernet header ipv4Packet.EthernetHeader = ethernetHeader.Bytes; // IP fields ipv4Packet.Version = 4; ipv4Packet.IPHeaderLength = IPv4Fields_Fields.IP_HEADER_LEN; ipv4Packet.IPTotalLength = content.Length - EthernetFields_Fields.ETH_HEADER_LEN; ipv4Packet.Id = 100; ipv4Packet.TimeToLive = 20; ipv4Packet.IPProtocol = IPProtocol.IPProtocolType.TCP; ipv4Packet.SourceAddress = device.Interface.Addresses[0].Addr.ipAddress; ipv4Packet.DestinationAddress = ipEndPoint.Address; ipv4Packet.ComputeIPChecksum(true); TCPPacket tcpPacket = new TCPPacket( EthernetFields_Fields.ETH_HEADER_LEN, content); // TCP fields tcpPacket.SourcePort = 2222; tcpPacket.DestinationPort = ipEndPoint.Port; tcpPacket.SequenceNumber = 1000; tcpPacket.AcknowledgmentNumber = 1000; tcpPacket.Syn = true; tcpPacket.TCPHeaderLength = TCPFields_Fields.TCP_HEADER_LEN; tcpPacket.WindowSize = 555; // Calculate checksum tcpPacket.ComputeTCPChecksum(true); try { device.Open(false, 20); device.SetFilter(String.Format("ip src {0} and tcp src port {1} and tcp dst port {2}", tcpPacket.DestinationAddress, tcpPacket.DestinationPort, tcpPacket.SourcePort)); // Send the packet device.SendPacket(tcpPacket); TCPPacket replyPacket = null; bool replyReceived = false; Stopwatch watch = new Stopwatch(); watch.Start(); // Condition including timeout check. while (watch.ElapsedMilliseconds < timeout && replyReceived != true) { if ((replyPacket = (TCPPacket)device.GetNextPacket()) != null) { replyReceived = true; } } if (!replyReceived) // A reply hasn't been received { return(ScanMessage.Timeout); } else if (replyPacket.Rst) // Remote host reset the connection { return(ScanMessage.PortClosed); } else if (replyPacket.Ack) // Remote host replied with a TCP packet { tcpPacket.Syn = false; tcpPacket.Rst = true; tcpPacket.WindowSize = 0; tcpPacket.ComputeTCPChecksum(true); device.SendPacket(tcpPacket); return(ScanMessage.PortOpened); } else { return(ScanMessage.Unknown); } } catch (Exception) { return(ScanMessage.Unknown); } finally { device.Close(); } }
private void Shutdown() { mTimer.Enabled = false; device?.StopCapture(); device?.Close(); }
public static void Main(string[] args) { string ver = SharpPcap.Version.VersionString; /* Print SharpPcap version */ Console.WriteLine("SharpPcap {0}, Example9.SendPacket.cs", ver); Console.WriteLine(); /* Retrieve the device list */ List<PcapDevice> devices = SharpPcap.Pcap.GetAllDevices(); /*If no device exists, print error */ if(devices.Count<1) { Console.WriteLine("No device found on this machine"); return; } Console.WriteLine("The following devices are available on this machine:"); Console.WriteLine("----------------------------------------------------"); Console.WriteLine(); int i=0; /* Scan the list printing every entry */ foreach(PcapDevice dev in devices) { /* Description */ Console.WriteLine("{0}) {1}",i,dev.Description); i++; } Console.WriteLine(); Console.Write("-- Please choose a device to send a packet on: "); i = int.Parse( Console.ReadLine() ); PcapDevice device = devices[i]; Console.Write("-- This will send a random packet out this interface, "+ "continue? [YES|no]"); string resp = Console.ReadLine().ToLower(); //If user refused, exit program if((resp!="")&&( !resp.StartsWith("y"))) { Console.WriteLine("Cancelled by user!"); return; } //Open the device device.Open(); //Generate a random packet byte[] bytes = GetRandomPacket(); try { //Send the packet out the network device device.SendPacket( bytes ); Console.WriteLine("-- Packet sent successfuly."); } catch(Exception e) { Console.WriteLine("-- "+ e.Message ); } //Close the pcap device device.Close(); Console.WriteLine("-- Device closed."); Console.Write("Hit 'Enter' to exit..."); Console.ReadLine(); }
/// <summary> /// Resolves the MAC address of the specified IP address /// </summary> /// <param name="destIP">The IP address to resolve</param> /// <param name="deviceName">The local network device name on which to send the ARP request</param> /// <returns>The MAC address that matches to the given IP address</returns> public PhysicalAddress Resolve(System.Net.IPAddress destIP, string deviceName) { PhysicalAddress localMAC = LocalMAC; System.Net.IPAddress localIP = LocalIP; //NetworkDevice device = new NetworkDevice(DeviceName); PcapDevice device = Pcap.GetPcapDevice(DeviceName); //FIXME: PcapDevices don't have IpAddress // These were present under Windows specific network adapters // and may be present in pcap in the future with pcap-ng // if no local ip address is specified use the one from the // local device #if false if (localIP == null) { localIP = device.IpAddress; } #endif // if no local mac address is specified use the one from the device if (LocalMAC == null) { localMAC = device.Interface.MacAddress; } //Build a new ARP request packet ARPPacket request = BuildRequest(destIP, localMAC, localIP); //create a "tcpdump" filter for allowing only arp replies to be read //String arpFilter = "arp and ether dst 00:1E:33:A6:FA:52"; String arpFilter = "arp and ether dst "; byte[] mac = localMAC.GetAddressBytes(); for (int i = 0; i < mac.Length; i++) { // Display the physical address in hexadecimal. arpFilter += mac[i].ToString("X2"); // Insert a hyphen after each byte, unless we are at the end of the // address. if (i != mac.Length - 1) { arpFilter += ":"; } } // arpFilter += mac; //open the device with 20ms timeout device.Open(true, 20); //set the filter device.SetFilter(arpFilter); //inject the packet to the wire device.SendPacket(request); ARPPacket reply; while (true) { //read the next packet from the network reply = (ARPPacket)device.GetNextPacket(); if (reply == null) { continue; } //if this is the reply we're looking for, stop if (reply.ARPSenderProtoAddress.Equals(destIP)) { break; } } //free the device device.Close(); //return the resolved MAC address return(reply.ARPSenderHwAddress); }
public static void Main(string[] args) { string ver = SharpPcap.Version.VersionString; /* Print SharpPcap version */ Console.WriteLine("SharpPcap {0}, Example4.BasicCapNoCallback.cs", ver); /* Retrieve the device list */ List <PcapDevice> devices = SharpPcap.Pcap.GetAllDevices(); /*If no device exists, print error */ if (devices.Count < 1) { Console.WriteLine("No device found on this machine"); return; } Console.WriteLine(); Console.WriteLine("The following devices are available on this machine:"); Console.WriteLine("----------------------------------------------------"); Console.WriteLine(); int i = 0; /* Scan the list printing every entry */ foreach (PcapDevice dev in devices) { /* Description */ Console.WriteLine("{0}) {1} {2}", i, dev.Name, dev.Description); i++; } Console.WriteLine(); Console.Write("-- Please choose a device to capture: "); i = int.Parse(Console.ReadLine()); PcapDevice device = devices[i]; //Open the device for capturing //true -- means promiscuous mode //1000 -- means a read wait of 1000ms device.Open(true, 1000); Console.WriteLine(); Console.WriteLine("-- Listenning on {0}...", device.Description); Packet packet; //Keep capture packets using PcapGetNextPacket() while ((packet = device.GetNextPacket()) != null) { // Prints the time and length of each received packet DateTime time = packet.PcapHeader.Date; uint len = packet.PcapHeader.PacketLength; Console.WriteLine("{0}:{1}:{2},{3} Len={4}", time.Hour, time.Minute, time.Second, time.Millisecond, len); } //Close the pcap device device.Close(); Console.WriteLine("-- Timeout (1000ms) elapsed, capture stopped, device closed."); Console.Write("Hit 'Enter' to exit..."); Console.ReadLine(); }
public static void Main(string[] args) { string ver = SharpPcap.Version.VersionString; /* Print SharpPcap version */ Console.WriteLine("SharpPcap {0}, Example6.DumpTCP.cs", ver); Console.WriteLine(); /* Retrieve the device list */ List <PcapDevice> devices = SharpPcap.Pcap.GetAllDevices(); /*If no device exists, print error */ if (devices.Count < 1) { Console.WriteLine("No device found on this machine"); return; } Console.WriteLine("The following devices are available on this machine:"); Console.WriteLine("----------------------------------------------------"); Console.WriteLine(); int i = 0; /* Scan the list printing every entry */ foreach (PcapDevice dev in devices) { /* Description */ Console.WriteLine("{0}) {1} {2}", i, dev.Name, dev.Description); i++; } Console.WriteLine(); Console.Write("-- Please choose a device to capture: "); i = int.Parse(Console.ReadLine()); PcapDevice device = devices[i]; //Register our handler function to the 'packet arrival' event device.OnPacketArrival += new SharpPcap.Pcap.PacketArrivalEvent(device_PcapOnPacketArrival); //Open the device for capturing //true -- means promiscuous mode //1000 -- means a read wait of 1000ms device.Open(true, 1000); //tcpdump filter to capture only TCP/IP packets string filter = "ip and tcp"; //Associate the filter with this capture device.SetFilter(filter); Console.WriteLine(); Console.WriteLine ("-- The following tcpdump filter will be applied: \"{0}\"", filter); Console.WriteLine ("-- Listenning on {0}, hit 'Ctrl-C' to exit...", device.Description); //Start capture 'INFINTE' number of packets device.Capture(SharpPcap.Pcap.INFINITE); //Close the pcap device //(Note: this line will never be called since // we're capturing infinite number of packets device.Close(); }
public static void Main(string[] args) { string ver = SharpPcap.Version.VersionString; /* Print SharpPcap version */ Console.WriteLine("SharpPcap {0}, Example3.BasicCap.cs", ver); /* Retrieve the device list */ List <PcapDevice> devices = SharpPcap.Pcap.GetAllDevices(); /*If no device exists, print error */ if (devices.Count < 1) { Console.WriteLine("No device found on this machine"); return; } Console.WriteLine(); Console.WriteLine("The following devices are available on this machine:"); Console.WriteLine("----------------------------------------------------"); Console.WriteLine(); int i = 0; /* Scan the list printing every entry */ foreach (PcapDevice dev in devices) { /* Description */ Console.WriteLine("{0}) {1} {2}", i, dev.Name, dev.Description); i++; } Console.WriteLine(); Console.Write("-- Please choose a device to capture: "); i = int.Parse(Console.ReadLine()); PcapDevice device = devices[i]; //Register our handler function to the 'packet arrival' event device.OnPacketArrival += new SharpPcap.Pcap.PacketArrivalEvent(device_PcapOnPacketArrival); //Open the device for capturing //true -- means promiscuous mode //1000 -- means a read wait of 1000ms device.Open(true, 1000); Console.WriteLine(); Console.WriteLine("-- Listenning on {0}, hit 'Enter' to stop...", device.Description); //Start the capturing process device.StartCapture(); //Wait for 'Enter' from the user. Console.ReadLine(); //Stop the capturing process device.StopCapture(); Console.WriteLine("-- Capture stopped."); //Close the pcap device device.Close(); }