// Open the file to parse // returns true if successful, false otherwise public bool openPcap(string capFile) { try { // Get an offline device device = new CaptureFileReaderDevice(capFile); // Open the device device.Open(); } catch (Exception e) { Console.WriteLine("Caught exception when opening file" + e.ToString()); Console.ReadKey(); return(false); } // Register our handler function to the 'packet arrival' event device.OnPacketArrival += new PacketArrivalEventHandler(device_OnPacketArrival); Console.WriteLine(); Console.WriteLine("-- Capturing from '{0}', hit 'Ctrl-C' to exit...", capFile); // Start capture 'INFINTE' number of packets // This method will return when EOF reached. device.Capture(); // Close the pcap device device.Close(); Console.WriteLine("-- End of file reached."); Console.Write("Hit 'Enter' to exit..."); Console.ReadLine(); return(true); }
/// <summary> /// This function opens an interface "Device" an starts looking /// for "jdnq" which are the ICMP-Like packets. /// </summary> public static void runn(ICaptureDevice device) { //Register our handler function to the 'packet arrival' event device.OnPacketArrival += new PacketArrivalEventHandler(device_OnPacketArrival); //Open the device for capturing int readTimeoutMilliseconds = 1000; device.Open(DeviceMode.Promiscuous, readTimeoutMilliseconds); // tcpdump filter to capture only icmp-like packets // "icmp" is "jdnq" string filter = shift("jdnq", -1); device.Filter = filter; // Start capture packets device.Capture(); // Close the pcap device // (Note: this line will never be called since // we're capturing infinite number of packets device.Close(); }
private void drpDevices_SelectedIndexChanged(object sender, EventArgs e) { if (selectedDevice != null && selectedDevice.Started) { selectedDevice.Close(); } if (drpDevices.SelectedIndex == -1) { return; } var index = drpDevices.SelectedIndex; selectedDevice = CaptureDeviceList.Instance[index]; selectedDevice.OnPacketArrival += new PacketArrivalEventHandler(device_OnPacketArrival); int readTimeoutMilliseconds = 1000; selectedDevice.Open(DeviceMode.Promiscuous, readTimeoutMilliseconds); string filter = "ip and tcp"; selectedDevice.Filter = filter; Task.Run(() => { selectedDevice.Capture(); }); }
public static void StartSniffing(ComboboxItem deviceItem) { PacketDataSource.Clear(); var devices = CaptureDeviceList.Instance; currentDevice = devices.Where(fn => fn.Name.Contains(deviceItem.Value.ToString())).FirstOrDefault(); //find device by name ID if (currentDevice != null) { try { //this needs more work, app is still slow and blocking arrivalEventHandler = new PacketArrivalEventHandler(device_OnPacketArrival); currentDevice.OnPacketArrival += arrivalEventHandler; BackgroundThreadStop = false; BackgroundThread = new System.Threading.Thread(RunBackgroundThread); BackgroundThread.Start(); currentDevice.Open(DeviceMode.Promiscuous, 1000); //string filter = "ip and tcp"; //device.Filter = filter; // Start capture 'INFINTE' number of packets currentDevice.Capture(); } catch { } } }
public static void Execute(ICaptureDevice device, IOutputFormatter output) { device.OnPacketArrival += Device_OnPacketArrival; device.Open(); device.Filter = "port 53"; device.Capture(); device.Close(); }
public void Execute(ICaptureDevice device) { device.OnPacketArrival += Device_OnPacketArrival; device.Open(); device.Filter = "tcp port 4061"; device.Capture(); device.Close(); }
public static void Execute(ICaptureDevice device, IOutputFormatter output) { device.OnPacketArrival += Device_OnPacketArrival; device.Open(); // enable processing only udp packets as CoAP is carried in UDP. device.Filter = "ip and udp"; device.Capture(); device.Close(); }
public PcapLoader(string FilePath) { var errorMsg = OpenCaptureFile(FilePath); if (errorMsg == null) { device.OnPacketArrival += new PacketArrivalEventHandler(OnPacketArrival); device.Capture(); device.Close(); } }
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(); }
/// <summary> /// 开始抓包方法,此方法用于后台线程中 /// </summary> /// <param name="device"></param> private void CaptureBackGround(ICaptureDevice device) { device.OnPacketArrival += Device_OnPacketArrival; //device.Open(); try { device.Filter = Common.filter; } catch (Exception) { MessageBox.Show("过滤器参数不合法"); return; } device.Capture(); }
//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 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(); }
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(); }
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(); }
public void Start() { if (is_start) { return; } is_start = true; int readTimeoutMilliseconds = 1000; device.Open(DeviceMode.Promiscuous, readTimeoutMilliseconds); new Thread(() => { try { device.Capture(); } catch (Exception) { this.Stop(); } }).Start(); }
public void Start() { _device.Filter = string.Format("tcp dst port {0} or tcp src port {0}", 44444); _device.OnPacketArrival += device_OnPacketArrival; if (_isFile) { _device.Capture(); //blocks infinitely (unless file) var e = OnStreamFinished; if (e != null) { e(this, new StreamFinishedEventArgs(_hadDiscovery)); } _device.Close(); } else { _device.StartCapture(); } }
void start() { if (captureDevice != null) { MessageBox.Show("Sniffer already started"); return; } try { CaptureDeviceList deviceList = CaptureDeviceList.Instance; captureDevice = deviceList[4]; captureDevice.OnPacketArrival += new PacketArrivalEventHandler(Program_OnPacketArrival); // открываем в режиме promiscuous, поддерживается также нормальный режим captureDevice.Open(DeviceMode.Promiscuous, 1000); // начинаем захват пакетов captureDevice.Capture(); } catch (Exception e) { MessageBox.Show(e.Message); } }
public void Start(string macAddress, string deviceAddress) { if (string.IsNullOrWhiteSpace(deviceAddress)) { return; } InterceptedMacAddress = macAddress; _deviceAddress = deviceAddress; _pcapDevice = SetupPcap(); if (_pcapDevice == null) { return; } _pcapMonitor = new Thread(() => { try { _pcapDevice.Capture(); } catch { lock (_pcapDevice) { Stop(); Start(InterceptedMacAddress, deviceAddress); } } }) { IsBackground = true }; _pcapMonitor.Start(); _packetTimer = new System.Timers.Timer(1000); _packetTimer.Elapsed += _packetTimer_Elapsed; _packetTimer.AutoReset = true; _packetTimer.Enabled = true; _packetTimer.Start(); }
static void Main(string[] args) { List <NetworkInterface> INTERFACES = new List <NetworkInterface> { }; foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces()) { INTERFACES.Add(nic); } for (int i = 0; i < INTERFACES.Count; i++) { Console.WriteLine("\n\n\t" + i + ". " + INTERFACES[i].Name); } bool flag = true; int number; CaptureDeviceList deviceList = CaptureDeviceList.Instance; string num; while (flag) { while (true) { Console.Write("\n\nEnter interface number: "); num = Console.ReadLine(); if (!(int.TryParse(num, out number))) { continue; } number = Convert.ToInt32(num); if (!(number > INTERFACES.Count || number < 0)) { break; } } if (number == INTERFACES.Count) { flag = false; } else { Console.WriteLine(); foreach (ICaptureDevice dev in CaptureDeviceList.Instance) { if (devName(dev.Name) == INTERFACES[number].Id) { Console.WriteLine(dev.Name); ICaptureDevice captured = dev; captured.OnPacketArrival += new PacketArrivalEventHandler(OnPacketArrival); captured.Open(DeviceMode.Promiscuous, 1000); captured.Capture(); } } } } }
public void Run() { var ver = Pcap.Version; /* Print SharpPcap version */ Console.WriteLine("SharpPcap {0}, Example6.DumpTCP.cs", ver); Console.WriteLine(); /* Retrieve the device list */ var devices = CaptureDeviceList.Instance; /*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 (var 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()); CaptureDevice = devices[i]; //Register our handler function to the 'packet arrival' event CaptureDevice.OnPacketArrival += device_OnPacketArrival; // Open the device for capturing int readTimeoutMilliseconds = 1000; CaptureDevice.Open(DeviceMode.Promiscuous, readTimeoutMilliseconds); ConnectionManager = new TcpConnectionManager(); ConnectionManager.OnConnectionFound += TcpConnectionManager_OnConnectionFound;; //tcpdump filter to capture only TCP/IP packets //host 109.105.133.76 and Logger.LogInformation("Ruoff Login: 5.63.132.147"); Logger.LogInformation("Ruoff shyeed Game: 109.105.133.76"); Console.WriteLine("-- Enter login server IP i.e. 127.0.0.1: "); var lognIp = Console.ReadLine(); Console.WriteLine("-- Enter game server IP i.e. 127.0.0.1: "); var gameIp = Console.ReadLine(); string filter = $"(host {(string.IsNullOrEmpty(gameIp) ? "109.105.133.76" : gameIp)} or " + $"host {(string.IsNullOrEmpty(lognIp) ? "5.63.132.147" : lognIp)}) and " + $"(tcp src port 2106 or " + "tcp dst port 2106 or " + "tcp src port 7777 or " + "tcp dst port 7777)"; //string filter = $"host {(string.IsNullOrEmpty(gameIp) ? "109.105.133.76" : gameIp)} and (tcp src port 7777 or tcp dst port 7777)"; Console.WriteLine($"Filter: {filter}"); CaptureDevice.Filter = filter; Console.WriteLine ("-- Listening on {0}, hit 'Ctrl-C' to exit...", CaptureDevice.Description); // Start capture 'INFINTE' number of packets CaptureDevice.Capture(); }
/* 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(); }
async UniTask DoStart() { await _privilegeRequester.WaitAllGranted(usingZi : false); Debug.Log("Finished Magic Leap privileges"); _captureDevice = Application.isEditor ? (ICaptureDevice) new EditorCaptureDevice() : (ICaptureDevice) new MLAsyncCaptureDevice(); _visionTextClient = new GVTextClient(_credentials); _textInterpreter = new TwitterHandleInterpreter(); _handleList.OnHandleSelected += handle => { OnHandleSelected(handle); }; _jpgTexture = new Texture2D(1, 1); _jpgImage.texture = _jpgTexture; _captureDevice.Enable(); _captureImage.texture = _captureDevice.GetPreviewTexture(); while (this) { _captureIndicator.SetActive(true); DateTime captureStart = DateTime.Now; byte[] image = await _captureDevice.Capture(); TimeSpan captureTime = DateTime.Now - captureStart; _jpgTexture.LoadImage(image); _jpgTexture.Apply(); _captureIndicator.SetActive(false); _annotateIndicator.SetActive(true); DateTime annotateStart = DateTime.Now; var annotation = await _visionTextClient.Annotate(image); TimeSpan annotateTime = DateTime.Now - annotateStart; Debug.Log($"Capture: {captureTime.TotalSeconds:0.0}, " + $"Annotate: {annotateTime.TotalSeconds:0.0}"); _annotateIndicator.SetActive(false); if (annotation == null) { Debug.LogWarning("Received null text annotation"); _annotateText.text = "<null>"; continue; } string text = annotation.Description; _annotateText.text = text.Replace("\n", " "); if (_textInterpreter.Interpret(text)) { Debug.Log("Found new handle(s)"); } _handleList.SetHandles(_textInterpreter.Handles); } }