예제 #1
0
        public BugSnifferService Init()
        {
            _logger.LogInformation($"Bugs! Sniffer Service using SharpPcap {SharpPcap.Version.VersionString}");
            _logger.LogInformation("Reading computer's network devices");

            CaptureDeviceList devices = CaptureDeviceList.Instance;

            if (devices.Count < 1)
            {
                _logger.LogError("COULD NOT FIND ANY DEVICES!!!!");
                throw new ArgumentNullException();
            }

            string localIPAddress = LocalIPAddress()?.ToString() ?? string.Empty;

            Console.WriteLine($"Your Local IP Address is {localIPAddress}");

            if (devices.Count(device => device.ToString().Contains(localIPAddress)) == 1)
            {
                _device = devices.Single(device => device.ToString().Contains(localIPAddress));
                _logger.LogInformation("Automatically Selected Device:");
                _logger.LogInformation(_device.ToString());
            }
            else
            {
                Console.WriteLine();
                Console.WriteLine("The following devices are available on this machine:");
                Console.WriteLine("----------------------------------------------------");
                Console.WriteLine();

                for (int i = 0; i < devices.Count; i++)
                {
                    Console.WriteLine($"-----------Device {i}-----------");
                    Console.WriteLine(devices[i].ToString());
                }

                Console.WriteLine("Usually device with local ip address is the correct one.");

                int deviceIndex = -1;

                do
                {
                    Console.Write("Please select which device you would like to use: ");

                    string input = Console.ReadLine();

                    deviceIndex = int.TryParse(input, out int result) ? result : -1;
                } while (deviceIndex < 0 || deviceIndex >= devices.Count);

                _device = devices[deviceIndex];

                _logger.LogInformation("Chosen Device:");
                _logger.LogInformation(_device.ToString());
            }

            _logger.LogInformation("Opening Device");
            _logger.LogInformation($"Using Timeout: {Timeout}");
            _device.Open(DeviceMode.Promiscuous, Timeout);

            return(this);
        }