Пример #1
0
        public Dictionary <string, string> Serialize()
        {
            var toReturn = new Dictionary <string, string>
            {
                { "DeviceType", DeviceType.ToString() },
                { "AddressType", AddressType.ToString() }
            };

            switch (AddressType)
            {
            case AddressType.MacAddress:
                toReturn["MacAddress"] = MacAddress.ToString();
                break;

            case AddressType.IpAddress:
                toReturn["IPAddress"] = IPAddress.ToString();
                if (Port.HasValue)
                {
                    toReturn["Port"] = Port.Value.ToString(CultureInfo.InvariantCulture);
                }
                break;

            default:
                throw new ArgumentOutOfRangeException();
            }

            return(toReturn);
        }
Пример #2
0
        public IEnumerable <ValidationResult> Validate(ValidationContext validationContext)
        {
            var errors = new List <ValidationResult>();

            if (string.IsNullOrWhiteSpace(MacAddress))
            {
                errors.Add(new ValidationResult(
                               errorMessage: "MAC-адрес не задан.",
                               memberNames: new string[] { "macAddress" }));
            }
            else
            {
                if (MacAddress.IsValidMacAddress() == false)
                {
                    errors.Add(new ValidationResult(
                                   errorMessage: "MAC-адрес некорректен.",
                                   memberNames: new string[] { "macAddress" }));
                }
            }
            if (string.IsNullOrWhiteSpace(IpAddress) == false)
            {
                if (IpAddress.IsValidIpAddress() == false)
                {
                    errors.Add(new ValidationResult(
                                   errorMessage: "IP-адрес некорректен.",
                                   memberNames: new string[] { "ipAddress" }));
                }
                if (string.IsNullOrWhiteSpace(SubnetMask))
                {
                    errors.Add(new ValidationResult(
                                   errorMessage: "Маска подсети не задана.",
                                   memberNames: new string[] { "subnetMask" }));
                }
                else
                {
                    if (SubnetMask.IsValidIpAddress() == false)
                    {
                        errors.Add(new ValidationResult(
                                       errorMessage: "Маска подсети некорректна.",
                                       memberNames: new string[] { "subnetMask" }));
                    }
                }
            }
            else
            {
                if (string.IsNullOrWhiteSpace(SubnetMask) == false)
                {
                    errors.Add(new ValidationResult(
                                   errorMessage: "IP-адрес не задан.",
                                   memberNames: new string[] { "ipAddress" }));
                    if (SubnetMask.IsValidIpAddress() == false)
                    {
                        errors.Add(new ValidationResult(
                                       errorMessage: "Маска подсети некорректна.",
                                       memberNames: new string[] { "subnetMask" }));
                    }
                }
            }
            return(errors);
        }
Пример #3
0
        public DeviceStateRequest GetState(MacAddress macAddress)
        {
            var request = new RestRequest("v1/state/{macAddress}", Method.GET)
            {
                RequestFormat = RestSharp.DataFormat.Json
            };

            request.AddParameter("macAddress", macAddress.Address);

            var response = client.Execute<StateModel>(request);

            if (response.StatusCode == HttpStatusCode.OK)
            {
                return DeviceStateRequest.From((DeviceState)Enum.Parse(typeof(DeviceState), response.Data.State), response.Data.ChangeDate, response.Data.Comment);
            }
            else if (response.StatusCode == HttpStatusCode.BadRequest)
            {
                Logger.Instance.Write("ApiComponent.GetState", LogLevel.Medium, String.Format("Resource '{0}' responded with unexpected HTTP code '{1}'. Message: {2}", request.Resource, response.StatusCode, response.Data.Comment));
                throw new InvalidOperationException(response.Data.Comment);
            }
            else if (response.StatusCode == HttpStatusCode.InternalServerError)
            {
                Logger.Instance.Write("ApiComponent.GetState", LogLevel.Medium, String.Format("Resource '{0}' responded with unexpected HTTP code '{1}'. Content: {2}", request.Resource, response.StatusCode, response.Content));
                throw new InvalidOperationException(String.Format("Unexpected error: {0}", response.Content));
            }
            else
            {
                Logger.Instance.Write("ApiComponent.GetState", LogLevel.Medium, String.Format("Resource '{0}' experienced an unexpected error: {1}", request.Resource, response.ErrorMessage));
                throw new InvalidOperationException(String.Format("Unexpected error: {0}", response.ErrorMessage));
            }
        }
Пример #4
0
        public DeviceStateRequest RequestApproval(Guid companyId, MacAddress macAddress, string comment)
        {
            var request = new RestRequest(String.Format("v1/state/{0}/pending", macAddress.Address), Method.POST)
            {
                RequestFormat = RestSharp.DataFormat.Json
            };

            request.AddBody(new { CompanyId = companyId, Comment = comment });

            var response = client.Execute<StateModel>(request);

            if (response.StatusCode == HttpStatusCode.Created)
            {
                return DeviceStateRequest.From((DeviceState)Enum.Parse(typeof(DeviceState), response.Data.State), response.Data.ChangeDate, comment);
            }
            else if(response.StatusCode == HttpStatusCode.BadRequest)
            {
                Logger.Instance.Write("ApiComponent.RequestApproval", LogLevel.Medium, String.Format("Resource '{0}' responded with unexpected HTTP code '{1}'. Message: {2}", request.Resource, response.StatusCode, response.Data.Comment));
                throw new InvalidOperationException(response.Data.Comment);
            }
            else
            {
                Logger.Instance.Write("ApiComponent.RequestApproval", LogLevel.Medium, String.Format("Resource '{0}' experienced an unexpected error: {1}", request.Resource, response.ErrorMessage));
                throw new InvalidOperationException(String.Format("Unexpected error. {0}", response.Data.Comment));
            }
        }
Пример #5
0
 /**
  * \fn getFormattedData
  */
 public String GetFormattedData()
 {
     return($"{Timestamp.ToString()};" +
            $"{MacAddress.macAdressLongToHexa(BluetoothAddress)};" +
            $"{LocalName};" +
            $"{Rssi};");
 }
Пример #6
0
        public bool SaveToFile(MacAddress mac)
        {
            var filePath = Utils.GetApplicationPath() + $"{mac.Value[0]}.txt";

            lock (lockObject)
            {
                try
                {
                    var fileContent = GetFileContent(filePath);
                    if (fileContent != null && fileContent.Length > 0)
                    {
                        var existMacValues = new List <string>();
                        existMacValues.AddRange(fileContent.ToString().Split(','));
                        if (existMacValues.Contains(mac.Value))
                        {
                            return(true);
                        }
                        existMacValues.Add(mac.Value);
                        existMacValues = existMacValues.OrderBy(x => x).ToList();
                        var dataToSave = string.Join(",", existMacValues);
                        File.WriteAllText(filePath, dataToSave);
                    }
                    else
                    {
                        File.AppendAllText(filePath, mac.Value);
                    }
                    return(true);
                } catch (Exception e)
                {
                    //TODO log errors
                    return(false);
                }
            }
        }
Пример #7
0
 private void HandleRouteError(
     MacAddress srcAddr,
     MacAddress dstAddr,
     ref Frame sdu)
 {
     Message.RouteError re = new Message.RouteError();
     if (re.ReadFromFrame(sdu))
     {
         // check message
         Trace.Print("Received " + re.ToString());
         if (re.UnreachableAddr != cInvalidShortAddr && srcAddr.Mode == MacAddressingMode.ShortAddress)
         {
             bool validRoute = _routingTable.HandleRouteError(re.UnreachableAddr, srcAddr.ShortAddress, re.FatalError);
             if (validRoute)
             {
                 if (re.TargetAddr == _addrShort)
                 { // sent to us
                     SendRouteRequest(re.UnreachableAddr);
                 }
                 else
                 { // forward error
                     if (re.HopsLeft > 0)
                     {
                         re.HopsLeft--;
                         SendRouteError(re);
                     }
                 }
             }
         }
     }
 }
Пример #8
0
        public ArpRequest(IpV4Address ipV4AddressToIdentify,
                          MacAddress requesterMacAddress, IpV4Address requesterIpV4Address,
                          Action <MacAddress> onIdentified)
        {
            if (requesterIpV4Address == ipV4AddressToIdentify)
            {
                throw new ArgumentException($"It doesn't make sense to ask {requesterIpV4Address} who {ipV4AddressToIdentify} is.");
            }

            IpV4AddressToIdentify = ipV4AddressToIdentify;
            RequesterMacAddress   = requesterMacAddress;
            RequesterIpV4Address  = requesterIpV4Address;
            OnIdentified          = onIdentified;
            EthernetLayer         = new EthernetLayer
            {
                Source      = requesterMacAddress,
                Destination = NetworkConstants.BroadcastMacAddress,
                EtherType   = EthernetType.Arp
            };

            ArpLayer = new ArpLayer
            {
                Operation             = ArpOperation.Request,
                ProtocolType          = EthernetType.IpV4,
                SenderHardwareAddress = requesterMacAddress.GetNetworkBytes().AsReadOnly(),
                SenderProtocolAddress = requesterIpV4Address.GetNetworkBytes().AsReadOnly(),
                TargetHardwareAddress = NetworkConstants.BroadcastMacAddress.GetNetworkBytes().AsReadOnly(),
                TargetProtocolAddress = ipV4AddressToIdentify.GetNetworkBytes().AsReadOnly()
            };

            PacketBuilder = new PacketBuilder(EthernetLayer, ArpLayer);
        }
Пример #9
0
        public void DataRequest(
            MacAddressingMode srcAddrMode,
            MacAddress dstAddr,
            UInt16 dstPanId,
            ref Frame msdu,
            Byte msduHandle,
            TxOptions options,
            SecurityOptions securityOptions,
            DataConfirmHandler handler)
        {
            TaskDataRequest task = new TaskDataRequest(
                srcAddrMode,
                dstAddr,
                dstPanId,
                msdu,
                msduHandle,
                options,
                securityOptions,
                handler);

            if (!_taskQueue.Add(task))
            {
                Frame.Release(ref msdu);
                if (handler != null)
                {
                    handler.Invoke(this, msduHandle, MacEnum.Congested);
                }
            }

            msdu = null; // in any case, remove frame ownership from caller
        }
Пример #10
0
        public override bool Setup()
        {
            //  Make sure everything we need is set

            // EUI
            if (string.IsNullOrEmpty(TestSequence.HUB_EUI))
            {
                TestErrorTxt = $"Hub EUI needs to be set before this test";
                return(false);
            }
            Regex regex = new Regex(@"[0-9a-fA-F]{16}");

            if (regex.Matches(TestSequence.HUB_EUI).Count != 1)
            {
                TestErrorTxt = $"Bad Hub EUI {TestSequence.HUB_EUI} provided";
                return(false);
            }
            _dbeui = DataUtils.GetEUI(TestSequence.HUB_EUI);

            // MAC
            if (string.IsNullOrEmpty(TestSequence.HUB_MAC_ADDR))
            {
                TestErrorTxt = $"Hub MAC address needs to be set before this test";
                return(false);
            }
            regex = new Regex(@"([0-9a-fA-F]{2}:){5}[0-9a-fA-F]{2}");
            if (regex.Matches(TestSequence.HUB_MAC_ADDR).Count != 1)
            {
                TestErrorTxt = $"Bad Hub MAc address {TestSequence.HUB_MAC_ADDR} provided";
                return(false);
            }
            _dbmac = DataUtils.GetMacAddress(TestSequence.HUB_MAC_ADDR);

            return(base.Setup());
        }
Пример #11
0
        public void RandomArpTest()
        {
            Random random = new Random();

            for (int i = 0; i != 1000; ++i)
            {
                MacAddress    ethernetSource = random.NextMacAddress();
                EthernetLayer ethernetLayer  = new EthernetLayer
                {
                    Source = ethernetSource,
                };

                ArpLayer arpLayer = random.NextArpLayer();

                Packet packet = PacketBuilder.Build(DateTime.Now, ethernetLayer, arpLayer);

                Assert.IsTrue(packet.IsValid, "IsValid");

                // Ethernet
                Assert.AreEqual(packet.Length - EthernetDatagram.HeaderLengthValue, packet.Ethernet.PayloadLength, "PayloadLength");

                Assert.AreEqual(ethernetSource, packet.Ethernet.Source, "Ethernet Source");
                Assert.AreEqual(EthernetDatagram.BroadcastAddress, packet.Ethernet.Destination, "Ethernet Destination");
                Assert.AreEqual(EthernetType.Arp, packet.Ethernet.EtherType, "Ethernet EtherType");

                // Arp
                Assert.AreEqual(ArpDatagram.HeaderBaseLength + 2 * arpLayer.SenderHardwareAddress.Count + 2 * arpLayer.SenderProtocolAddress.Count, packet.Ethernet.Arp.Length, "Arp length");
                Assert.AreEqual(ArpHardwareType.Ethernet, packet.Ethernet.Arp.HardwareType, "Arp hardware type");
                Assert.AreEqual(arpLayer, packet.Ethernet.Arp.ExtractLayer(), "ARP Layer");
                Assert.AreNotEqual(arpLayer, random.NextArpLayer(), "ARP Layer");
                Assert.AreEqual(arpLayer.GetHashCode(), packet.Ethernet.Arp.ExtractLayer().GetHashCode(), "ARP Layer");
                ArpLayer differentArpLayer = random.NextArpLayer();
                Assert.AreNotEqual(arpLayer.GetHashCode(), differentArpLayer.GetHashCode(), "ARP Layer");
            }
        }
Пример #12
0
        public MacAddress GetMacAddressById(int mac_address_id)
        {
            MacAddress           mac_address      = new MacAddress();
            List <PackageObject> mac_address_list = GetAllMacAddress();

            if (mac_address_list != null)
            {
                if (mac_address_list != null)
                {
                    foreach (MacAddress element in mac_address_list)
                    {
                        if (element.id == mac_address_id)
                        {
                            mac_address.id      = mac_address_id;
                            mac_address.user_id = element.user_id;
                            mac_address.value   = element.value;
                            return(mac_address);
                        }
                    }
                }
                return(mac_address);
            }
            else
            {
                return(null);
            }
        }
Пример #13
0
 /// <summary>
 ///     Reader Constracter for reader info
 /// </summary>
 /// <param name="macAddress">Mac Address of reader</param>
 /// <param name="frequency">Signal Frequency of reader</param>
 /// <param name="x">X Cordinate of Reader</param>
 /// <param name="y">Y Cordinate of Reader</param>
 public Reader(MacAddress macAddress, uint frequency, int x, int y)
 {
     MacAddress = macAddress;
     Frequency  = frequency;
     X          = x;
     Y          = y;
 }
Пример #14
0
            public PanasonicDiscovery(PhysicalAddress macAddress, IPAddress _ip)
            {
                byte[] ipBytes;
                UInt32 ipUInt32;

                _uint32_04 = NetworkUtils.bigEndian32(0x000d0000);
                _uint32_08 = NetworkUtils.bigEndian32(0x00000000);

                headerMagic = NetworkUtils.bigEndian32(0x00010000);

                mac = macAddress.GetAddressBytes().GetStruct <MacAddress>();

                ipBytes  = _ip.GetAddressBytes();
                ipUInt32 = (UInt32)((ipBytes[0] << 24) |
                                    (ipBytes[1] << 16) |
                                    (ipBytes[2] << 8) |
                                    (ipBytes[3]));
                ip = NetworkUtils.bigEndian32(ipUInt32);

                _uint32_16 = NetworkUtils.bigEndian32(0x00012011);
                _uint32_1A = NetworkUtils.bigEndian32(0x1e11231f);
                _uint32_1E = NetworkUtils.bigEndian32(0x1e191300);
                _uint32_22 = NetworkUtils.bigEndian32(0x00020000);
                _uint32_26 = NetworkUtils.bigEndian32(0x00000000);
                _uint32_2A = NetworkUtils.bigEndian32(0x00000000);
                _uint32_2E = NetworkUtils.bigEndian32(0x0000ffff);
                checksum   = NetworkUtils.bigEndian16(0x0000);
            }
Пример #15
0
        private void addStaticEntryBtn_Click(object sender, RoutedEventArgs e)
        {
            IPv4Address ip  = null;
            MacAddress  mac = null;

            try
            {
                ip = new IPv4Address(staticEntryIp.Text);
            }
            catch { }
            try
            {
                mac = new MacAddress(staticEntryMac.Text);
            }
            catch { }

            if (ip == null && mac == null)
            {
                MessageBox.Show("You did not enter a valid IP and MAC address.");
            }
            else if (ip == null)
            {
                MessageBox.Show("\"" + staticEntryIp.Text + "\" is not a valid IP address.");
            }
            else if (mac == null)
            {
                MessageBox.Show("\"" + staticEntryMac.Text + "\" is not a valid MAC address.");
            }
            else
            {
                // We are good to go
                Client.Arp.AddStaticEntry(ip, mac);
            }
        }
Пример #16
0
        /// <summary>
        /// Creates a magic package for the target computer's given MAC address.
        /// </summary>
        /// <param name="macAddress">MAC address of the computer to wake up</param>
        /// <returns>The magic package for waking the computer up.</returns>
        private static byte[] CreateMagicPackage(MacAddress macAddress)
        {
            if (macAddress == null || macAddress.Bytes == null)
                throw new ArgumentNullException("macAddress");
            if (macAddress.Bytes.Length != 6)
                throw new ArgumentException("macAddress must have length of 6 bytes");

            byte[] package = new byte[102];

            // 6 bytes of 0xFF
            for (int i = 0; i < 6; i++)
            {
                package[i] = 0xFF;
            }

            // sixteen repititions of MAC address
            for (int i = 1; i < 17; i++)
            {
                for (int j = 0; j < 6; j++)
                {
                    package[i * 6 + j] = macAddress.Bytes[j];
                }
            }

            return package;
        }
Пример #17
0
        //Constructor for sender
        public DosSender(string sourceIp, string destIp, MacAddress destMac, MacAddress sourceMac, string host, string slowLorisKeepAliveData, string slowLorisHeaderNotComplete, int slowPostHeaderContentLength, string slowPostHeader, string slowReadUrl, int startPort, int portStep, bool ddos = false, ushort slowReadWindowSize = 100)
        {
            if (ddos)
            {
                var randomNumber = Rand.Next() % DosController.FakeIpV4Addresses.Count;
                Console.WriteLine(randomNumber);
                SourceIpV4 = DosController.FakeIpV4Addresses[randomNumber];
            }
            else
            {
                SourceIpV4 = new IpV4Address(sourceIp);
            }

            DestinationIpV4            = new IpV4Address(destIp);
            SourceMac                  = sourceMac;
            DestinationMac             = destMac;
            SlowLorisHeaderNotComplete = slowLorisHeaderNotComplete;
            SlowPostHeader             = slowPostHeader + $"\r\nContent-Length: {slowPostHeaderContentLength}\r\n\r\n";
            SlowReadUrl                = slowReadUrl;
            WindowSize                 = slowReadWindowSize;
            SlowPostContentLength      = slowPostHeaderContentLength;
            SlowLorisKeepAliveData     = slowLorisKeepAliveData;
            Host            = host;
            SourcePort      = (ushort)(startPort + NextSourcePort);
            NextSourcePort += (ushort)portStep;
        }
Пример #18
0
        /// <summary>
        /// Reads the Frame Address portion of the message header.
        /// See http://lan.developer.lifx.com/docs/header-description for more details.
        /// </summary>
        /// <param name="buffer">The buffer to read from.</param>
        private void ReadFrameAddress(MemoryStream buffer)
        {
            Debug.Assert(buffer != null);

            // The first 8 bytes contain the 6-byte Target MAC Address, right padded with zeros.
            //
            byte[] target = buffer.ReadBytes(8);
            Target = new MacAddress(target);

            // The next 6 bytes are unused and marked "Reserved".
            //
            byte[] oblivion = buffer.ReadBytes(6);

            // The next byte contains bitflags about the message where byte:
            //  [0]: res_required
            //  [1]: ack_required
            //
            byte flags = buffer.LittleEndianReadByte();

            ResponseRequired = (flags & (1 << 0)) != 0;
            AckRequired      = (flags & (1 << 1)) != 0;

            // The last byte is the Message's sequence number.
            //
            SequenceNumber = buffer.LittleEndianReadByte();
        }
Пример #19
0
    public TrackerDataBaseBlock(byte[] rawBytes)
    {
        Size = BitConverter.ToUInt32(rawBytes, 0);

        Signature = ExtraDataTypes.TrackerDataBlock;
        Version   = BitConverter.ToInt32(rawBytes, 8);
        MachineId = CodePagesEncodingProvider.Instance.GetEncoding(1252).GetString(rawBytes, 16, 16).Split('\0').First();

        var guidRaw0 = new byte[16];
        var guidRaw1 = new byte[16];
        var guidRaw2 = new byte[16];
        var guidRaw3 = new byte[16];

        Buffer.BlockCopy(rawBytes, 0x20, guidRaw0, 0, 16);
        Buffer.BlockCopy(rawBytes, 0x30, guidRaw1, 0, 16);
        Buffer.BlockCopy(rawBytes, 0x40, guidRaw2, 0, 16);
        Buffer.BlockCopy(rawBytes, 0x50, guidRaw3, 0, 16);

        VolumeDroid      = new Guid(guidRaw0);
        FileDroid        = new Guid(guidRaw1);
        VolumeDroidBirth = new Guid(guidRaw2);
        FileDroidBirth   = new Guid(guidRaw3);

        var tempMac = FileDroid.ToString().Split('-').Last();

        MacAddress = Regex.Replace(tempMac, ".{2}", "$0:");
        MacAddress = MacAddress.Substring(0, MacAddress.Length - 1);

        CreationTime = GetDateTimeOffsetFromGuid(FileDroid);
    }
Пример #20
0
        public static List <byte> GetBytesList(this MacAddress address)
        {
            UInt48 value = address.ToValue();

            byte[] array = BitConverter.GetBytes(value).Take(6).ToArray();
            return(array.Reverse().ToList());
        }
Пример #21
0
        public static string GetDeviceMac()
        {
            MacAddress address       = AllDevices[DeviceId].GetMacAddress();
            string     addressString = address.ToString();

            return(addressString);
        }
        private static void CompareEthernetAddress(XElement element, MacAddress address)
        {
            foreach (var field in element.Fields())
            {
                switch (field.Name())
                {
                case "eth.addr":
                case "eth.dst_resolved":
                case "eth.addr_resolved":
                case "eth.src_resolved":
                    field.AssertShow(address.ToString().ToLower());
                    field.AssertNoFields();
                    break;

                case "eth.ig":
                case "eth.lg":
                    field.AssertNoFields();
                    break;

                case "_ws.expert":
                    field.AssertNumFields(4);
                    break;

                default:
                    throw new InvalidOperationException("Invalid ethernet address field " + field.Name());
                }
            }
        }
Пример #23
0
 private void performDs4Output()
 {
     lock (outputReport)
     {
         int lastError = 0;
         while (true)
         {
             if (writeOutput())
             {
                 lastError = 0;
                 if (testRumble.IsRumbleSet())          // repeat test rumbles periodically; rumble has auto-shut-off in the DS4 firmware
                 {
                     Monitor.Wait(outputReport, 10000); // DS4 firmware stops it after 5 seconds, so let the motors rest for that long, too.
                 }
                 else
                 {
                     Monitor.Wait(outputReport);
                 }
             }
             else
             {
                 int thisError = Marshal.GetLastWin32Error();
                 if (lastError != thisError)
                 {
                     Console.WriteLine(MacAddress.ToString() + " " + System.DateTime.UtcNow.ToString("o") + "> encountered write failure: " + thisError);
                     lastError = thisError;
                 }
             }
         }
     }
 }
Пример #24
0
        public bool Ping(IpV4Address IP, MacAddress Mac, int Count = 10)
        {
            this._target_ip  = IP;
            this._target_mac = Mac;
            bool Result = false;

            for (ushort SequenceNumber = 1; SequenceNumber < Count; SequenceNumber++)
            {
                _ping_echo_wait_handle.Reset();
                _current_icmp_sequence_num = SequenceNumber;
                SendIcmpEcho(_target_ip, _target_mac, SequenceNumber);
                VirtualNetwork.Instance.PostTraceMessage(string.Format("PING {0} ({1})", _target_ip.ToString(), SequenceNumber), false);
                _current_state = ICMP_STATE.WAIT_ECHO;
                if (_ping_echo_wait_handle.WaitOne(PING_ECHO_TIMEOUT))
                {
                    VirtualNetwork.Instance.PostTraceMessage(" - OK");
                    Result = true;
                }
                else
                {
                    VirtualNetwork.Instance.PostTraceMessage(" - TIMEOUT");
                }
                _current_state = ICMP_STATE.IDLE;
                Thread.Sleep(1000);
            }
            return(Result);
        }
Пример #25
0
 public Client(string pHostname, IPAddress pIPAddress, byte[] pTransactionId, MacAddress pMacAddress)
 {
     hostname      = pHostname;
     ipaddress     = pIPAddress;
     transactionId = pTransactionId;
     macAddress    = pMacAddress;
 }
        private static void CompareEthernetAddress(XElement element, MacAddress address)
        {
            foreach (var field in element.Fields())
            {
                switch (field.Name())
                {
                    case "eth.addr":
                    case "eth.dst_resolved":
                    case "eth.addr_resolved":
                    case "eth.src_resolved":
                        field.AssertShow(address.ToString().ToLower());
                        field.AssertNoFields();
                        break;

                    case "eth.ig":
                    case "eth.lg":
                        field.AssertNoFields();
                        break;

                    case "_ws.expert":
                        field.AssertNumFields(4);
                        break;

                    default:
                        throw new InvalidOperationException("Invalid ethernet address field " + field.Name());
                }
            }
        }
Пример #27
0
        //INITIALIZATION
        public void init()
        {
            InitializeComponent();
            Show();
            allDevices          = LivePacketDevice.AllLocalMachine;
            thr_list            = new List <Thread>();
            htLog               = new Hashtable();
            downcntDev0         = upcntDev0 = downcntDev1 = upcntDev1 =
                downUdp0        = upUdp0 = downTcp0 = upTcp0 = downArp0 = upArp0 = downIcmp0 = upIcmp0 = downDropped0 = upDropped0 =
                    downUdp1    = upUdp1 = downTcp1 = upTcp1 = downArp1 = upArp1 = downIcmp1 = upIcmp1 = downDropped1 = upDropped1 =
                        downIp0 = downIp1 = upIp0 = upIp1 = 0;
            enabled             = false;

            //open communcators
            dev0 = allDevices[DEV0].Open(SNAPSHOT, PacketDeviceOpenAttributes.Promiscuous | PacketDeviceOpenAttributes.NoCaptureLocal, TIMEOUT);
            thr_list.Add(new Thread(Receiving0));
            thr_list[0].Start();

            dev1 = allDevices[DEV1].Open(SNAPSHOT, PacketDeviceOpenAttributes.Promiscuous | PacketDeviceOpenAttributes.NoCaptureLocal, TIMEOUT);
            thr_list.Add(new Thread(Receiving1));
            thr_list[1].Start();

            myMAC1    = PcapDotNet.Core.Extensions.LivePacketDeviceExtensions.GetMacAddress(allDevices[DEV0]);
            myMAC2    = PcapDotNet.Core.Extensions.LivePacketDeviceExtensions.GetMacAddress(allDevices[DEV1]);
            this.Text = (myMAC1.ToString() + " - " + myMAC2.ToString());

            hashDev0 = new Hashtable();
            hashDev1 = new Hashtable();
        }
Пример #28
0
        /// <summary>
        /// This function builds the Ethernet Row Data Packet with every third channel set to a color.
        /// </summary>
        private Packet BuildTestPacket(MacAddress source, MacAddress destination, int row, int pixelsWidth, int dataOffset, byte color, int testOffset)
        {
            int offset = 0;
            int width  = pixelsWidth * 3;

            byte[] mainByte = new byte[(width) + 7];

            EthernetType type = ((EthernetType)0x5500);

            if (row < 256)
            {
                type        = ((EthernetType)0x5500);
                mainByte[0] = Convert.ToByte(row);
            }
            else
            {
                type        = ((EthernetType)0x5501);
                mainByte[0] = Convert.ToByte(row % 256);
            }

            EthernetLayer ethernetLayer = new EthernetLayer
            {
                Source      = source,
                Destination = destination,
                EtherType   = type
            };

            //mainByte[0] = Convert.ToByte(row);
            mainByte[1] = Convert.ToByte(offset >> 8);
            mainByte[2] = Convert.ToByte(offset & 0xFF);
            mainByte[3] = Convert.ToByte(pixelsWidth >> 8);
            mainByte[4] = Convert.ToByte(pixelsWidth & 0xFF);
            mainByte[5] = 0x08;
            mainByte[6] = 0x80;

            for (int i = 0; i < width; i++)
            {
                int  indexwHead = 7 + i;
                byte oldValue   = 0;
                if (i % 3 == testOffset)
                {
                    oldValue = color;
                }
                //int oldint = Convert.ToInt32(data[i + (fullDataOffset * 3)]);
                int  newint   = ((oldValue * _brightness) / 100);
                byte newValue = Convert.ToByte(newint);
                mainByte[indexwHead] = newValue;
                //mainByte[indexwHead] = 0x88;
            }

            PayloadLayer payloadLayer =
                new PayloadLayer
            {
                Data = new Datagram(mainByte)
            };

            PacketBuilder builder = new PacketBuilder(ethernetLayer, payloadLayer);

            return(builder.Build(DateTime.Now));
        }
Пример #29
0
        public List <PackageObject> GetAllMacAddress()
        {
            List <PackageObject> mac_address_list = new List <PackageObject>();

            if (File.Exists(mac_address_db_path))
            {
                using (StreamReader sr = File.OpenText(mac_address_db_path))
                {
                    string   line = "";
                    string[] line_element;
                    while ((line = sr.ReadLine()) != null)
                    {
                        line_element = line.Split(';');
                        MacAddress mac_address = new MacAddress();
                        mac_address.id      = Convert.ToInt32(line_element[0]);
                        mac_address.user_id = Convert.ToInt32(line_element[1]);
                        mac_address.value   = line_element[2];
                        mac_address_list.Add(mac_address);
                    }
                }
                return(mac_address_list);
            }
            else
            {
                return(null);
            }
        }
Пример #30
0
        /// <summary>
        /// This function builds the Ethernet 0x0AFF Packet.
        /// </summary>
        private Packet BuildSecondPacket(MacAddress source, MacAddress destination)
        {
            EthernetLayer ethernetLayer = new EthernetLayer
            {
                Source      = source,
                Destination = destination,
                EtherType   = ((EthernetType)0x0AFF)
            };

            byte[] mainByte = new byte[63];

            mainByte[0] = 0xFF;
            mainByte[1] = 0xFF;
            mainByte[2] = 0xFF;

            PayloadLayer payloadLayer =
                new PayloadLayer
            {
                Data = new Datagram(mainByte)
            };

            PacketBuilder builder = new PacketBuilder(ethernetLayer, payloadLayer);

            return(builder.Build(DateTime.Now));
        }
Пример #31
0
        void Arp_ArpReplyReceived(IPv4Address ip, MacAddress mac)
        {
            IPv4Address myip = null;

            string myText = "";

            this.Dispatcher.Invoke(() =>
            {
                myText = ipToResolve.Text;
            });

            try
            {
                myip = new IPv4Address(myText);
                if (ip.AsString == myip.AsString || !IPv4Address.IsInSameSubnet(myip, ip, Client.Configuration.SubnetMask))
                {
                    this.Dispatcher.Invoke(() =>
                    {
                        arpAnswers.Items.Add(mac.ToString());
                    });
                }
            }
            catch
            { }
        }
Пример #32
0
        public override int GetHashCode()
        {
            int prime  = 31;
            int result = 1;

            result = prime * result + Id.BitShiftThenBitOr(prime);
            result = prime * result + Name.StringToInt().BitShiftThenBitOr(prime);
            result = prime * result + Gender.GenderToInt().BitShiftThenBitOr(prime);
            result = prime * result + BirthDate.DateToInt().BitShiftThenBitOr(prime);
            result = prime * result + Email.StringToInt().BitShiftThenBitOr(prime);
            result = prime * result + Phone.StringToInt().BitShiftThenBitOr(prime);
            result = prime * result + ZipCode.BitShiftThenBitOr(prime);
            result = prime * result + Address.StringToInt().BitShiftThenBitOr(prime);
            result = prime * result + UserName.StringToInt().BitShiftThenBitOr(prime);
            result = prime * result + Password.StringToInt().BitShiftThenBitOr(prime);
            result = prime * result + Pin.BitShiftThenBitOr(prime);
            result = prime * result + LoginIP.StringToInt().BitShiftThenBitOr(prime);
            result = prime * result + MacAddress.StringToInt().BitShiftThenBitOr(prime);
            result = prime * result + StartingDate.DateToInt().BitShiftThenBitOr(prime);
            result = prime * result + Access.AccessToInt().BitShiftThenBitOr(prime);
            result = prime * result + AccountPriority.AccountPriorityToInt().BitShiftThenBitOr(prime);
            result = prime * result + MembershipType.MembershipToInt().BitShiftThenBitOr(prime);
            result = prime * result + Email.StringToInt().BitShiftThenBitOr(prime);
            result = prime * result + BirthDate.ToString().StringToInt().BitShiftThenBitOr(prime);
            result = prime * result + LastLogin.DateToInt().BitShiftThenBitOr(prime);
            result = prime * result + LastLogout.DateToInt().BitShiftThenBitOr(prime);
            result = prime * result + Age.BitShiftThenBitOr(prime);
            return(result);
        }
Пример #33
0
        public ArpReply(MacAddress sourceMacAddress, IpV4Address sourceIpv4Address,
                        MacAddress targetMacAddress, IpV4Address targetIpv4Address)
        {
            SourceMacAddress  = sourceMacAddress;
            SourceIpv4Address = sourceIpv4Address;
            TargetMacAddress  = targetMacAddress;
            TargetIpv4Address = targetIpv4Address;

            EthernetLayer = new EthernetLayer
            {
                Source      = SourceMacAddress,
                Destination = targetMacAddress,
                EtherType   = EthernetType.Arp
            };

            ArpLayer = new ArpLayer
            {
                Operation             = ArpOperation.Reply,
                ProtocolType          = EthernetType.IpV4,
                SenderHardwareAddress = SourceMacAddress.GetNetworkBytes().AsReadOnly(),
                SenderProtocolAddress = SourceIpv4Address.GetNetworkBytes().AsReadOnly(),
                TargetHardwareAddress = TargetMacAddress.GetNetworkBytes().AsReadOnly(),
                TargetProtocolAddress = TargetIpv4Address.GetNetworkBytes().AsReadOnly()
            };

            PacketBuilder = new PacketBuilder(EthernetLayer, ArpLayer);
        }
        public static Packet NextEthernetPacket(this Random random, int packetSize, DateTime timestamp, MacAddress ethernetSource, MacAddress ethernetDestination)
        {
            if (packetSize < EthernetDatagram.HeaderLengthValue)
                throw new ArgumentOutOfRangeException("packetSize", packetSize,
                                                      "Must be at least the ethernet header length (" + EthernetDatagram.HeaderLengthValue + ")");

            return PacketBuilder.Build(timestamp,
                                       new EthernetLayer
                                       {
                                           Source = ethernetSource,
                                           Destination = ethernetDestination,
                                           EtherType = random.NextEthernetType()
                                       },
                                       random.NextPayloadLayer(packetSize - EthernetDatagram.HeaderLengthValue));
        }
Пример #35
0
 public static ArpData Create(string deviceID, IPAddress ipAddress, MacAddress macAddress, SystemModule module)
 {
     var arp = new ArpData(deviceID, ipAddress, macAddress, module);
     arp._timer = new Timer
                 {
                     Interval = 1000
                 };
     arp._timer.Elapsed += (s, e) =>
     {
         arp._ttl--;
         if (arp._ttl == 0)
         {
             Log.Write("ArpData", "Timeout", string.Format("ip={0}, mac={1}", arp.IP.StandardFormat, arp.Mac.StandardFormat));
             arp._timer.Stop();
             module.KillArpData(arp);
         }
     };
     return arp;
 }
Пример #36
0
        private static void WakeOnLan(MacAddress macAddress)
        {
            // Das WOL Signal wird als Broadcast verschickt.
            // Es enthält 6x 0xFF, direkt danach folgt 16x die MAC Adresse.

            using (UdpClient client = new UdpClient())
            {
                client.Connect(IPAddress.Broadcast, 0);

                byte[] wolSignal = new byte[6 + MacAddress.MAC_ADDRESS_LENGTH * 16];

                // Startsignal einfügen
                START_SIGNAL.CopyTo(wolSignal, 0);

                // Die Mac-Adresse wird 16x in das WOL Signal angehängt
                for (int i = 0; i < 16; i++)
                {
                    macAddress.Address.CopyTo(wolSignal, START_SIGNAL.Length + i * MacAddress.MAC_ADDRESS_LENGTH);
                }

                // Signal senden
                client.Send(wolSignal, wolSignal.Length);
            }
        }
Пример #37
0
        /// <summary>
        /// Once a client is connect this callback will be reached.
        /// Client sends the mac address to the server at this time.
        /// </summary>
        /// <param name="ar">Results from the connection.</param>
        private void ConnectCallback(IAsyncResult ar)
        {
            try
            {
                // Retrieve the socket from the state object.
                var client = (ClientHandler) ar.AsyncState;
                // Complete the connection.
                client.ClientSocket.EndConnect(ar);
                client.ClientSocket.BeginReceive(client.Buffer, 0, ClientHandler.BufferSize, 0,
                    ReceiveCallback, client);
                var macInfo = new MacAddress();
                var macAddr =
                (
                    from nic in NetworkInterface.GetAllNetworkInterfaces()
                    where nic.OperationalStatus == OperationalStatus.Up
                    select nic.GetPhysicalAddress().ToString()
                ).FirstOrDefault();

                macInfo.MAddress = macAddr;
                client.Send(macInfo);
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }
        }
Пример #38
0
 internal static void WriteHeader(byte[] buffer, int offset, MacAddress ethernetSource, MacAddress ethernetDestination, EthernetType ethernetType)
 {
     buffer.Write(offset + Offset.Source, ethernetSource, Endianity.Big);
     buffer.Write(offset + Offset.Destination, ethernetDestination, Endianity.Big);
     buffer.Write(offset + Offset.EtherTypeLength, (ushort)ethernetType, Endianity.Big);
 }
Пример #39
0
        // Callback function invoked by libpcap for every incoming packet
        private static void PacketHandler(Packet packet)
        {
            #if DEBUG
            // print timestamp and length of the packet
            Log.DebugFormat("{0} length: {1}", packet.Timestamp.ToString("yyyy-MM-dd hh:mm:ss.fff"), packet.Length);
            #endif

            var ip = packet.Ethernet.IpV4;
            var udp = ip.Udp;

            #if DEBUG
            // print ip addresses and udp ports
            Log.DebugFormat("{0}:{1} -> {2}:{3}", ip.Source, udp.SourcePort, ip.Destination, udp.DestinationPort);
            #endif

            // get first six bytes from payload
            var magicPacketStart = BitConverter.ToString(udp.Payload.Subsegment(0, 6).ToArray());

            if (string.CompareOrdinal(magicPacketStart, "FF-FF-FF-FF-FF-FF") != 0)
                return;

            var dstMac =
                new MacAddress(BitConverter.ToString(udp.Payload.Subsegment(6, 6).ToArray()).Replace("-", ":"));

            Log.InfoFormat("New WOL-Packet with destination MAC {0} detected", dstMac);

            lock (SyncLock)
            {
                Log.Debug("Entering save zone");

                foreach (var protobufChannel in ClientList)
                {
                    Log.InfoFormat("Forwarding magic packet to client {0}", protobufChannel.Key);
                    protobufChannel.Value.SendAsync(new MagicPacket
                    {
                        BroadcastAddress = ip.Destination.ToString(),
                        MacAddress = dstMac.ToString()
                    });
                    Log.InfoFormat("Magic packet forwarded");
                }

                Log.Debug("Leaving save zone");
            }
        }
Пример #40
0
 public void Setup(string desc, IPAddress ipAddr, MacAddress macAddr)
 {
     ipAddress = ipAddr;
     macAddress = macAddr;
     description = desc;
 }
Пример #41
0
        private byte[] CreateMagicPacket(MacAddress macAddress)
        {
            //Magic packet  contains a 6-bytes trailer and 16 times a 6-bytes sequence containing the MAC address
            byte[] magicPacket = new byte[17 * 6];

            //setup trailer
            for (int i = 0; i < 6; i++)
            {
                magicPacket[i] = 0xFF;
            }

            //now the body
            for (int i = 1; i <= 16; i++)
            {
                for (int j = 0; j < 6; j++)
                {
                    magicPacket[i * 6 + j] = macAddress[j];
                }
            }
            return magicPacket;
        }
Пример #42
0
 public RemoteServer(string desc, IPAddress ipAddr, MacAddress macAddr)
 {
     Setup(desc, ipAddr, macAddr);
 }
Пример #43
0
        private void buttonSend00_Click(object sender, EventArgs e)
        {
            PacketDevice senderDevice = LivePacketDevice.AllLocalMachine[comboInterface.SelectedIndex];

             using (PacketCommunicator communicator = senderDevice.Open(100, PacketDeviceOpenAttributes.Promiscuous, 1000))
             {
                 for (int j = 0; j < 1; j++)
                 {
                     MacAddress sourceMac = new MacAddress(textSourceMac.Text);
                     MacAddress destinationMac = new MacAddress(textDestinationMac.Text);

                     EthernetLayer ethernetLayer = new EthernetLayer
                     {
                         Source = sourceMac,
                         Destination = destinationMac
                     };

                     IpV4Layer ipv4Layer = new IpV4Layer
                     {
                         Source = new IpV4Address(textSourceIP.Text),
                         CurrentDestination = new IpV4Address(textDestinationIP.Text),
                         HeaderChecksum = null,
                         Identification = 123,
                         Options = IpV4Options.None,
                         Protocol = null,
                         Ttl = 100,
                         TypeOfService = 0,

                     };

                     UdpLayer udpLayer = new UdpLayer
                     {
                         SourcePort = (ushort)Convert.ToUInt16(textSourcePort.Text),
                         DestinationPort = (ushort)Convert.ToUInt16(textDestinationPort.Text),
                         Checksum = null,
                         CalculateChecksumValue = true,
                     };

                     byte[] buff = new byte[128];
                     // goo size
                     //byte[] buff = new byte[192];

                     // monlist
                     buff[0] = 0x17;
                     buff[1] = 0x00;
                     buff[2] = 0x03;

                     // monlist
                     buff[3] = 0x2a;

                     // memstats
                     // buff[3] = 0x07;

                     PayloadLayer payloadLayer = new PayloadLayer
                     {

                         Data = new Datagram(buff),
                         // Data = new Datagram(Encoding.ASCII.GetBytes("hello world")),
                     };

                     PacketBuilder builder = new PacketBuilder(ethernetLayer, ipv4Layer, udpLayer, payloadLayer);

                     communicator.SendPacket(builder.Build(DateTime.Now));
                 }
             }
        }
Пример #44
0
        public void RandomIpV6Test()
        {
            MacAddress ethernetSource = new MacAddress("00:01:02:03:04:05");
            MacAddress ethernetDestination = new MacAddress("A0:A1:A2:A3:A4:A5");
            const EthernetType EthernetType = EthernetType.IpV6;

            EthernetLayer ethernetLayer = new EthernetLayer
                                              {
                                                  Source = ethernetSource,
                                                  Destination = ethernetDestination,
                                                  EtherType = EthernetType
                                              };

            int seed = new Random().Next();
            Console.WriteLine("Seed: " + seed);
            Random random = new Random(seed);

            for (int i = 0; i != 1000; ++i)
            {
                IpV6Layer ipV6Layer = random.NextIpV6Layer(false);

                PayloadLayer payloadLayer = random.NextPayloadLayer(random.NextInt(0, 50 * 1024));

                List<ILayer> layers = new List<ILayer> {ethernetLayer, ipV6Layer};
                if (ipV6Layer.ExtensionHeaders.LastHeader != IpV4Protocol.EncapsulatingSecurityPayload)
                    layers.Add(payloadLayer);
                Packet packet = PacketBuilder.Build(DateTime.Now, layers);

                Assert.IsTrue(ipV6Layer.LastNextHeader == IpV4Protocol.Ip ||
                              ipV6Layer.LastNextHeader == IpV4Protocol.IpV6||
                              ipV6Layer.LastNextHeader == IpV4Protocol.Udp ||
                              ipV6Layer.LastNextHeader == IpV4Protocol.Tcp ||
                              ipV6Layer.LastNextHeader == IpV4Protocol.InternetGroupManagementProtocol ||
                              ipV6Layer.LastNextHeader == IpV4Protocol.InternetControlMessageProtocol ||
                              ipV6Layer.LastNextHeader == IpV4Protocol.Gre ||
                              packet.IsValid, string.Format("IsValid ({0}...{1})", ipV6Layer.NextHeader, ipV6Layer.ExtensionHeaders.NextHeader));

                // Ethernet
                Assert.AreEqual(packet.Length - EthernetDatagram.HeaderLengthValue, packet.Ethernet.PayloadLength, "PayloadLength");
                Assert.AreEqual(ethernetLayer, packet.Ethernet.ExtractLayer(), "Ethernet Layer");

                // IpV6
                Assert.AreEqual(ipV6Layer, packet.Ethernet.IpV6.ExtractLayer(), "IP Layer");
                Assert.AreEqual(ipV6Layer.GetHashCode(), packet.Ethernet.IpV6.ExtractLayer().GetHashCode(), "IP Layer");
                Assert.AreEqual(string.Format("{0} -> {1} ({2})", ipV6Layer.Source, ipV6Layer.CurrentDestination, ipV6Layer.NextHeader), ipV6Layer.ToString());
                IEnumerator extensionHeadersEnumerator = ((IEnumerable)packet.Ethernet.IpV6.ExtensionHeaders).GetEnumerator();
                for (int extensionHeaderIndex = 0; extensionHeaderIndex != packet.Ethernet.IpV6.ExtensionHeaders.Headers.Count; ++extensionHeaderIndex)
                {
                    IpV6ExtensionHeader extensionHeader = packet.Ethernet.IpV6.ExtensionHeaders[extensionHeaderIndex];
                    Assert.IsTrue(extensionHeadersEnumerator.MoveNext());
                    Assert.AreEqual(extensionHeader, extensionHeadersEnumerator.Current);
                    IpV6ExtensionHeader layerExtensionheader = ipV6Layer.ExtensionHeaders[extensionHeaderIndex];
                    Assert.AreEqual(extensionHeader, layerExtensionheader);
                    Assert.AreEqual(extensionHeader.GetHashCode(), layerExtensionheader.GetHashCode());
                    IpV6ExtensionHeaderOptions extensionHeaderOptions = extensionHeader as IpV6ExtensionHeaderOptions;
                    if (extensionHeaderOptions != null)
                    {
                        foreach (IpV6Option option in extensionHeaderOptions.Options)
                        {
                            switch (option.OptionType)
                            {
                                case IpV6OptionType.SimplifiedMulticastForwardingDuplicatePacketDetection:
                                    IpV6OptionSimplifiedMulticastForwardingDuplicatePacketDetection optionSimplifiedMulticastForwardingDuplicatePacketDetection = (IpV6OptionSimplifiedMulticastForwardingDuplicatePacketDetection)option;
                                    Assert.AreEqual(optionSimplifiedMulticastForwardingDuplicatePacketDetection is IpV6OptionSimplifiedMulticastForwardingDuplicatePacketDetectionSequenceHashAssistValue, optionSimplifiedMulticastForwardingDuplicatePacketDetection.HashIndicator);
                                    break;

                                case IpV6OptionType.QuickStart:
                                    IpV6OptionQuickStart optionQuickStart = (IpV6OptionQuickStart)option;
                                    MoreAssert.IsBiggerOrEqual(0, optionQuickStart.RateKbps);
                                    break;
                            }
                        }
                    }
                    IpV6ExtensionHeaderMobility extensionHeaderMobility = extensionHeader as IpV6ExtensionHeaderMobility;
                    if (extensionHeaderMobility != null)
                    {
                        Assert.IsFalse(extensionHeaderMobility.Equals(2));
                        Assert.IsTrue(extensionHeaderMobility.Equals((object)extensionHeader));
                        Assert.AreEqual(extensionHeaderMobility.MobilityOptions, new IpV6MobilityOptions(extensionHeaderMobility.MobilityOptions).AsEnumerable());
                        foreach (IpV6MobilityOption option in extensionHeaderMobility.MobilityOptions)
                        {
                            switch (option.OptionType)
                            {
                                case IpV6MobilityOptionType.BindingIdentifier:
                                    IpV6MobilityOptionBindingIdentifier optionBindingIdentifier = (IpV6MobilityOptionBindingIdentifier)option;
                                    if (optionBindingIdentifier.IpV4CareOfAddress.HasValue)
                                        Assert.AreEqual(optionBindingIdentifier.IpV4CareOfAddress.Value, optionBindingIdentifier.CareOfAddress);
                                    else if (optionBindingIdentifier.IpV6CareOfAddress.HasValue)
                                        Assert.AreEqual(optionBindingIdentifier.IpV6CareOfAddress.Value, optionBindingIdentifier.CareOfAddress);
                                    else
                                        Assert.IsNull(optionBindingIdentifier.CareOfAddress);
                                    break;

                                case IpV6MobilityOptionType.AccessNetworkIdentifier:
                                    IpV6MobilityOptionAccessNetworkIdentifier optionAccessNetworkIdentifier = (IpV6MobilityOptionAccessNetworkIdentifier)option;
                                    foreach (IpV6AccessNetworkIdentifierSubOption subOption in optionAccessNetworkIdentifier.SubOptions)
                                    {
                                        switch (subOption.OptionType)
                                        {
                                            case IpV6AccessNetworkIdentifierSubOptionType.GeoLocation:
                                                IpV6AccessNetworkIdentifierSubOptionGeoLocation subOptionGeoLocation =
                                                    (IpV6AccessNetworkIdentifierSubOptionGeoLocation)subOption;
                                                MoreAssert.IsBiggerOrEqual(-90, subOptionGeoLocation.LatitudeDegreesReal);
                                                MoreAssert.IsSmallerOrEqual(90, subOptionGeoLocation.LatitudeDegreesReal);
                                                MoreAssert.IsBiggerOrEqual(-180, subOptionGeoLocation.LongitudeDegreesReal);
                                                MoreAssert.IsSmallerOrEqual(180, subOptionGeoLocation.LongitudeDegreesReal);
                                                IpV6AccessNetworkIdentifierSubOptionGeoLocation subOptionGetLocationFromReal =
                                                    IpV6AccessNetworkIdentifierSubOptionGeoLocation.CreateFromRealValues(
                                                        subOptionGeoLocation.LatitudeDegreesReal,
                                                        subOptionGeoLocation.LongitudeDegreesReal);
                                                Assert.AreEqual(subOptionGeoLocation, subOptionGetLocationFromReal);
                                                break;
                                        }
                                    }
                                    break;

                                case IpV6MobilityOptionType.Timestamp:
                                    IpV6MobilityOptionTimestamp optionTimestamp = (IpV6MobilityOptionTimestamp)option;
                                    MoreAssert.IsBiggerOrEqual(new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc), optionTimestamp.TimestampDateTime);
                                    break;

                                case IpV6MobilityOptionType.FlowIdentification:
                                    IpV6MobilityOptionFlowIdentification optionFlowIdentification = (IpV6MobilityOptionFlowIdentification)option;
                                    foreach (IpV6FlowIdentificationSubOption subOption in optionFlowIdentification.SubOptions)
                                    {
                                        switch (subOption.OptionType)
                                        {
                                            case IpV6FlowIdentificationSubOptionType.BindingReference:
                                                IpV6FlowIdentificationSubOptionBindingReference subOptionBindingReference =
                                                    (IpV6FlowIdentificationSubOptionBindingReference)subOption;
                                                Assert.AreEqual(subOptionBindingReference,
                                                                new IpV6FlowIdentificationSubOptionBindingReference(
                                                                    subOptionBindingReference.BindingIds.AsEnumerable()));
                                                break;
                                        }
                                    }
                                    break;

                                case IpV6MobilityOptionType.CryptographicallyGeneratedAddressParameters:
                                    IpV6MobilityOptionCryptographicallyGeneratedAddressParameters optionCryptographicallyGeneratedAddressParameters = (IpV6MobilityOptionCryptographicallyGeneratedAddressParameters)option;
                                    Assert.AreEqual(optionCryptographicallyGeneratedAddressParameters.Length - 2, optionCryptographicallyGeneratedAddressParameters.CryptographicallyGeneratedAddressParameters.Length);
                                    break;

                                case IpV6MobilityOptionType.CareOfTest:
                                    IpV6MobilityOptionCareOfTest optionCareOfTest = (IpV6MobilityOptionCareOfTest)option;
                                    Assert.IsInstanceOfType(optionCareOfTest.CareOfKeygenToken, typeof(ulong));
                                    break;

                                case IpV6MobilityOptionType.IpV4CareOfAddress:
                                    IpV6MobilityOptionIpV4CareOfAddress optionIpV4CareOfAddress = (IpV6MobilityOptionIpV4CareOfAddress)option;
                                    Assert.IsNotNull(optionIpV4CareOfAddress.CareOfAddress);
                                    break;

                                case IpV6MobilityOptionType.ReplayProtection:
                                    IpV6MobilityOptionReplayProtection optionReplayProtection = (IpV6MobilityOptionReplayProtection)option;
                                    Assert.IsNotNull(optionReplayProtection.Timestamp);
                                    break;

                                case IpV6MobilityOptionType.Experimental:
                                    IpV6MobilityOptionExperimental optionExperimental = (IpV6MobilityOptionExperimental)option;
                                    Assert.IsNotNull(optionExperimental.Data);
                                    break;

                                case IpV6MobilityOptionType.PermanentHomeKeygenToken:
                                    IpV6MobilityOptionPermanentHomeKeygenToken optionPermanentHomeKeygenToken =
                                        (IpV6MobilityOptionPermanentHomeKeygenToken)option;
                                    Assert.IsNotNull(optionPermanentHomeKeygenToken.PermanentHomeKeygenToken);
                                    break;

                                case IpV6MobilityOptionType.Signature:
                                    IpV6MobilityOptionSignature optionSignature = (IpV6MobilityOptionSignature)option;
                                    Assert.IsNotNull(optionSignature.Signature);
                                    break;
                            }
                        }
                    }
                }
            }
        }
Пример #45
0
 public void MacAddressBadStringErrorTest()
 {
     MacAddress address = new MacAddress("12:34:56:78");
     Assert.IsNotNull(address);
     Assert.Fail();
 }
Пример #46
0
        public override bool Init()
        {
            bool result = Load(GUIGraphicsContext.Skin + @"\MyMovies.xml");

            try
            {
                using (MediaPortal.Profile.Settings xmlreader = new MediaPortal.Profile.Settings(Config.GetFile(Config.Dir.Config, "MediaPortal.xml")))
                {
                    _currentLayout      = (LayoutOptions)xmlreader.GetValueAsInt("MyMovies", "layout", (int)LayoutOptions.List);
                    _currentView        = (Views)xmlreader.GetValueAsInt("MyMovies", "view", (int)_currentView);
                    _currentSorting     = (Sorting.Options)xmlreader.GetValueAsInt("MyMovies", "sorting", (int)_currentSorting);
                    CurrentUser         = xmlreader.GetValueAsInt("MyMovies", "currentUser", CurrentUser);
                    _sortAscending      = xmlreader.GetValueAsBool("MyMovies", "sortDirection", _sortAscending);
                    _programDataPath    = xmlreader.GetValueAsString("MyMovies", "txtProgramDataPath", @"C:\ProgramData\My Movies\FileStorage");
                    _serverName         = xmlreader.GetValueAsString("MyMovies", "txtServerName", "localhost");
                    _dbInstance         = xmlreader.GetValueAsString("MyMovies", "txtDBInstance", "MYMOVIES");
                    _userName           = xmlreader.GetValueAsString("MyMovies", "txtUserName", string.Empty);
                    _password           = xmlreader.GetValueAsString("MyMovies", "txtPassword", string.Empty);
                    _storedPIN          = xmlreader.GetValueAsString("MyMovies", "txtPINCode", "4321");
                    _chkRemoteWakeup    = xmlreader.GetValueAsBool("MyMovies", "chkRemoteWakeup", false);
                    _macAddress         = MacAddress.Parse(xmlreader.GetValueAsString("MyMovies", "MACAddress", "00-00-00-00-00-00"));
                    _ipAddress          = IPAddress.Parse(xmlreader.GetValueAsString("MyMovies", "IPAddress", "0.0.0.0"));
                    _wakeupRetries      = xmlreader.GetValueAsInt("MyMovies", "wakeupRetries", 3);
                    _wakeupRetryTimeout = xmlreader.GetValueAsInt("MyMovies", "wakeupRetryTimeout", 3000);
                    _maxConfiguredRating= xmlreader.GetValueAsInt("MyMovies", "maximumViewableRating", 4);

                    string xml = xmlreader.GetValueAsString("MyMovies", "xmlPathReplacement", string.Empty);
                    _driveReplacements  = new DriveReplacements(xml);

                    string xmlUsers = xmlreader.GetValueAsString("MyMovies", "xmlUsers", string.Empty);
                    _availableUsers = new Users(xmlUsers);
                }

                Log.Info(string.Format("MyMovies::Init - RemoteWakeup {0}, MAC {1}, IP {2}", _chkRemoteWakeup, _macAddress, _ipAddress));
            }
            catch (Exception ex)
            {
                Log.Error("MyMovies::Init - Cannot load settings");
                Log.Error(ex);
            }

            // Determine the maximum assigned rating within the DB.
            _maxRating = GetMaximumRating();

            g_Player.PlayBackStopped += new g_Player.StoppedHandler(OnPlayBackStopped);
            g_Player.PlayBackChanged += new g_Player.ChangedHandler(OnPlayBackChanged);
            g_Player.PlayBackEnded += new g_Player.EndedHandler(OnPlayBackEnded);

            return result;
        }
 public static Packet NextEthernetPacket(this Random random, int packetSize, MacAddress ethernetSource, MacAddress ethernetDestination)
 {
     return random.NextEthernetPacket(packetSize, DateTime.Now, ethernetSource, ethernetDestination);
 }
Пример #48
0
        public void RandomTcpTest()
        {
            MacAddress ethernetSource = new MacAddress("00:01:02:03:04:05");
            MacAddress ethernetDestination = new MacAddress("A0:A1:A2:A3:A4:A5");

            EthernetLayer ethernetLayer = new EthernetLayer
                                              {
                                                  Source = ethernetSource,
                                                  Destination = ethernetDestination
                                              };

            int seed = new Random().Next();
            Console.WriteLine("Seed: " + seed);
            Random random = new Random(seed);

            for (int i = 0; i != 1000; ++i)
            {
                IpV4Layer ipV4Layer = random.NextIpV4Layer(null);
                ipV4Layer.HeaderChecksum = null;
                IpV6Layer ipV6Layer = random.NextIpV6Layer(IpV4Protocol.Tcp, false);

                EthernetType ethernetType = random.NextBool() ? EthernetType.IpV4 : EthernetType.IpV6;
                Layer ipLayer = (ethernetType == EthernetType.IpV4 ? (Layer)ipV4Layer : ipV6Layer);
                TcpLayer tcpLayer = random.NextTcpLayer();

                PayloadLayer payloadLayer = random.NextPayloadLayer(random.Next(60000));

                Packet packet = PacketBuilder.Build(DateTime.Now, ethernetLayer, ipLayer, tcpLayer, payloadLayer);

                Assert.IsTrue(packet.IsValid);

                // Ethernet
                ethernetLayer.EtherType = ethernetType;
                Assert.AreEqual(ethernetLayer, packet.Ethernet.ExtractLayer(), "Ethernet Layer");
                ethernetLayer.EtherType = EthernetType.None;

                // Ip.
                if (ipLayer == ipV4Layer)
                {
                    // IpV4.
                    ipV4Layer.Protocol = IpV4Protocol.Tcp;
                    ipV4Layer.HeaderChecksum = ((IpV4Layer)packet.Ethernet.IpV4.ExtractLayer()).HeaderChecksum;
                    Assert.AreEqual(ipV4Layer, packet.Ethernet.IpV4.ExtractLayer(), "IPv4 Layer");
                    ipV4Layer.HeaderChecksum = null;
                } 
                else
                {
                    Assert.AreEqual(ipV6Layer, packet.Ethernet.IpV6.ExtractLayer(), "IPv6 Layer");
                }

                // TCP
                tcpLayer.Checksum = packet.Ethernet.Ip.Tcp.Checksum;
                Assert.AreEqual(tcpLayer, packet.Ethernet.Ip.Tcp.ExtractLayer(), "TCP Layer");
                Assert.AreNotEqual(random.NextTcpLayer(), packet.Ethernet.Ip.Tcp.ExtractLayer(), "TCP Layer");
                Assert.AreEqual(tcpLayer.GetHashCode(), packet.Ethernet.Ip.Tcp.ExtractLayer().GetHashCode(), "TCP Layer");
                Assert.AreNotEqual(random.NextTcpLayer().GetHashCode(), packet.Ethernet.Ip.Tcp.ExtractLayer().GetHashCode(), "TCP Layer");
                Assert.AreEqual((uint)(packet.Ethernet.Ip.Tcp.SequenceNumber + packet.Ethernet.Ip.Tcp.PayloadLength), packet.Ethernet.Ip.Tcp.NextSequenceNumber);
                foreach (TcpOption option in packet.Ethernet.Ip.Tcp.Options.OptionsCollection)
                {
                    Assert.AreEqual(option, option);
                    Assert.AreEqual(option.GetHashCode(), option.GetHashCode());
                    Assert.IsFalse(string.IsNullOrEmpty(option.ToString()));
                    Assert.IsFalse(option.Equals(null));
                    Assert.IsFalse(option.Equals(2));
                }
                Assert.AreEqual(tcpLayer.Options, packet.Ethernet.Ip.Tcp.Options, "Options");
                Assert.AreEqual((tcpLayer.ControlBits & TcpControlBits.Acknowledgment) == TcpControlBits.Acknowledgment, packet.Ethernet.Ip.Tcp.IsAcknowledgment, "IsAcknowledgment");
                Assert.AreEqual((tcpLayer.ControlBits & TcpControlBits.CongestionWindowReduced) == TcpControlBits.CongestionWindowReduced, packet.Ethernet.Ip.Tcp.IsCongestionWindowReduced, "IsCongestionWindowReduced");
                Assert.AreEqual((tcpLayer.ControlBits & TcpControlBits.ExplicitCongestionNotificationEcho) == TcpControlBits.ExplicitCongestionNotificationEcho, packet.Ethernet.Ip.Tcp.IsExplicitCongestionNotificationEcho, "IsExplicitCongestionNotificationEcho");
                Assert.AreEqual((tcpLayer.ControlBits & TcpControlBits.Fin) == TcpControlBits.Fin, packet.Ethernet.Ip.Tcp.IsFin, "IsFin");
                Assert.AreEqual((tcpLayer.ControlBits & TcpControlBits.Push) == TcpControlBits.Push, packet.Ethernet.Ip.Tcp.IsPush, "IsPush");
                Assert.AreEqual((tcpLayer.ControlBits & TcpControlBits.Reset) == TcpControlBits.Reset, packet.Ethernet.Ip.Tcp.IsReset, "IsReset");
                Assert.AreEqual((tcpLayer.ControlBits & TcpControlBits.Synchronize) == TcpControlBits.Synchronize, packet.Ethernet.Ip.Tcp.IsSynchronize, "IsSynchronize");
                Assert.AreEqual((tcpLayer.ControlBits & TcpControlBits.Urgent) == TcpControlBits.Urgent, packet.Ethernet.Ip.Tcp.IsUrgent, "IsUrgent");
                Assert.AreEqual(0, packet.Ethernet.Ip.Tcp.Reserved);
                Assert.IsFalse(packet.Ethernet.Ip.Tcp.IsChecksumOptional, "IsChecksumOptional");
                Assert.AreEqual(TcpDatagram.HeaderMinimumLength + tcpLayer.Options.BytesLength + payloadLayer.Length, packet.Ethernet.Ip.Tcp.Length, "Total Length");
                Assert.IsTrue(packet.Ethernet.Ip.IsTransportChecksumCorrect, "IsTransportChecksumCorrect");

                Assert.AreEqual(payloadLayer.Data, packet.Ethernet.Ip.Tcp.Payload, "Payload");
            }
        }
Пример #49
0
        public void RandomIpV4Test()
        {
            MacAddress ethernetSource = new MacAddress("00:01:02:03:04:05");
            MacAddress ethernetDestination = new MacAddress("A0:A1:A2:A3:A4:A5");
            const EthernetType EthernetType = EthernetType.IpV4;

            EthernetLayer ethernetLayer = new EthernetLayer
                                              {
                                                  Source = ethernetSource,
                                                  Destination = ethernetDestination,
                                                  EtherType = EthernetType
                                              };

            Random random = new Random();

            for (int i = 0; i != 1000; ++i)
            {
                IpV4Layer ipV4Layer = random.NextIpV4Layer();
                ipV4Layer.HeaderChecksum = null;

                PayloadLayer payloadLayer = random.NextPayloadLayer(random.NextInt(0, 50 * 1024));

                Packet packet = PacketBuilder.Build(DateTime.Now, ethernetLayer, ipV4Layer, payloadLayer);

                Assert.IsTrue(ipV4Layer.Protocol == IpV4Protocol.Udp ||
                              ipV4Layer.Protocol == IpV4Protocol.Tcp ||
                              ipV4Layer.Protocol == IpV4Protocol.InternetGroupManagementProtocol ||
                              ipV4Layer.Protocol == IpV4Protocol.InternetControlMessageProtocol ||
                              ipV4Layer.Protocol == IpV4Protocol.Gre ||
                              packet.IsValid, "IsValid (" + ipV4Layer.Protocol + ")");

                // Ethernet
                Assert.AreEqual(packet.Length - EthernetDatagram.HeaderLengthValue, packet.Ethernet.PayloadLength, "PayloadLength");
                Assert.AreEqual(ethernetLayer, packet.Ethernet.ExtractLayer(), "Ethernet Layer");

                // IpV4
                ipV4Layer.HeaderChecksum = ((IpV4Layer)packet.Ethernet.IpV4.ExtractLayer()).HeaderChecksum;
                Assert.AreEqual(ipV4Layer, packet.Ethernet.IpV4.ExtractLayer(), "IP Layer");
                Assert.AreEqual(ipV4Layer.Destination, packet.Ethernet.IpV4.Destination, "Destination");
                Assert.AreNotEqual(ipV4Layer, null);
                Assert.AreNotEqual(ipV4Layer, new PayloadLayer());
                Assert.IsNotNull(ipV4Layer.ToString());
                Assert.AreEqual(IpV4Datagram.HeaderMinimumLength + ipV4Layer.Options.BytesLength, packet.Ethernet.IpV4.HeaderLength, "IP HeaderLength");
                Assert.AreEqual(packet.Length - EthernetDatagram.HeaderLengthValue, packet.Ethernet.IpV4.TotalLength, "IP TotalLength");
                Assert.AreNotEqual(2, packet.Ethernet.IpV4.Fragmentation, "IP Fragmentation");
                Assert.IsTrue(ipV4Layer.Fragmentation == packet.Ethernet.IpV4.Fragmentation, "IP Fragmentation");
                Assert.IsFalse(ipV4Layer.Fragmentation != packet.Ethernet.IpV4.Fragmentation, "IP Fragmentation");
                Assert.IsFalse(ipV4Layer.Fragmentation.Equals(0), "IP Fragmentation");
                if (ipV4Layer.Fragmentation.Offset != 0)
                    Assert.AreNotEqual(ipV4Layer.Fragmentation, IpV4Fragmentation.None, "IP Fragmentation");
                Assert.AreEqual(ipV4Layer.Fragmentation.GetHashCode(), packet.Ethernet.IpV4.Fragmentation.GetHashCode(), "IP Fragmentation");
                Assert.AreEqual(ipV4Layer.Fragmentation.Options, packet.Ethernet.IpV4.Fragmentation.Options, "IP Fragmentation");
                Assert.AreEqual(ipV4Layer.Fragmentation.Offset, packet.Ethernet.IpV4.Fragmentation.Offset, "IP Fragmentation");
                if (ipV4Layer.Fragmentation.Equals(IpV4Fragmentation.None))
                {
                    Assert.AreEqual(IpV4FragmentationOptions.None, packet.Ethernet.IpV4.Fragmentation.Options, "IP Fragmentation");
                    Assert.AreEqual(0, packet.Ethernet.IpV4.Fragmentation.Offset, "IP Fragmentation");
                }
                Assert.AreEqual(true, packet.Ethernet.IpV4.IsHeaderChecksumCorrect, "IP HeaderChecksumCorrect");
                Assert.AreNotEqual(null, packet.Ethernet.IpV4.Options, "IP Options");
                Assert.AreNotEqual(packet.Ethernet.IpV4.Options, null, "IP Options");
                Assert.AreNotEqual(new IpV4Options(new IpV4OptionUnknown(0, new byte[35])), packet.Ethernet.IpV4.Options, "IP Options");
                Assert.AreEqual(ipV4Layer.Options.GetHashCode(), packet.Ethernet.IpV4.Options.GetHashCode(), "IP Options HashCode");
                Assert.IsNotNull(packet.Ethernet.IpV4.Options.ToString());
                for (int optionIndex = 0; optionIndex != ipV4Layer.Options.Count; ++optionIndex)
                {
                    IpV4Option option = ipV4Layer.Options[optionIndex];
                    Assert.AreEqual(option, packet.Ethernet.IpV4.Options[optionIndex]);
                    Assert.IsFalse(option.Equals(null));
                }

                if (packet.Ethernet.IpV4.Protocol == IpV4Protocol.Tcp)
                    Assert.IsInstanceOfType(packet.Ethernet.IpV4.Transport, typeof(TcpDatagram));
                else if (packet.Ethernet.IpV4.Protocol == IpV4Protocol.Udp)
                    Assert.IsInstanceOfType(packet.Ethernet.IpV4.Transport, typeof(UdpDatagram));
                else
                    Assert.IsNull(packet.Ethernet.IpV4.Transport);

                Assert.AreEqual(payloadLayer.Data, packet.Ethernet.IpV4.Payload, "IP Payload");
            }
        }
Пример #50
0
 private void PackageLayer2AndSend(String deviceID, MacAddress source, MacAddress destination, ushort layer3Type, PacketData data, Action callback)
 {
     byte[] layerIdByteArray = BitConverter.GetBytes(layer3Type);
     if (BitConverter.IsLittleEndian)
     {
         Array.Reverse(layerIdByteArray);
     }
     var ethernetHeader =
             (EthernetHeader)Controller.GetSingletonHandler("ETHERNETII").Build(
                                 Value.Raw("EthernetHeader:Destination", destination),
                                 Value.Raw("EthernetHeader:Source", source),
                                 Value.Raw("EthernetHeader:TypeOrLength", TypeOrLength.From(layerIdByteArray)));
     var newData = GeneratePacketData(data, ethernetHeader);
     Log.Write("System", "Send", "length:" + newData.Length + ", from: " + destination.StandardFormat + ", to: " + source.StandardFormat);
     Send(deviceID, newData);
     callback();
 }
Пример #51
0
        static void Main(string[] args)
        {
            // Send anonymous statistics about the usage of Pcap.Net
            PcapDotNet.Analysis.PcapDotNetAnalysis.OptIn = true;

            // Retrieve the device list from the local machine
            IList<LivePacketDevice> allDevices = LivePacketDevice.AllLocalMachine;

            if (allDevices.Count == 0)
            {
                Console.WriteLine("No interfaces found! Make sure WinPcap is installed.");
                return;
            }

            // Print the list
            for (int i = 0; i != allDevices.Count; ++i)
            {
                LivePacketDevice device = allDevices[i];
                Console.Write((i + 1) + ". " + device.Name);
                if (device.Description != null)
                    Console.WriteLine(" (" + device.Description + ")");
                else
                    Console.WriteLine(" (No description available)");
            }

            int deviceIndex = 0;
            do
            {
                Console.WriteLine("Enter the interface number (1-" + allDevices.Count + "):");
                string deviceIndexString = Console.ReadLine();
                if (!int.TryParse(deviceIndexString, out deviceIndex) ||
                    deviceIndex < 1 || deviceIndex > allDevices.Count)
                {
                    deviceIndex = 0;
                }
            } while (deviceIndex == 0);

            // Take the selected adapter
            PacketDevice selectedDevice = allDevices[deviceIndex - 1];

            // Open the output device
            using (PacketCommunicator communicator = selectedDevice.Open(100, // name of the device
                                                                         PacketDeviceOpenAttributes.Promiscuous, // promiscuous mode
                                                                         1000)) // read timeout
            {
                // Supposing to be on ethernet, set mac source to 1:1:1:1:1:1
                MacAddress source = new MacAddress("1:1:1:1:1:1");

                // set mac destination to 2:2:2:2:2:2
                MacAddress destination = new MacAddress("2:2:2:2:2:2");

                // Create the packets layers

                // Ethernet Layer
                EthernetLayer ethernetLayer = new EthernetLayer
                                                  {
                                                      Source = source,
                                                      Destination = destination
                                                  };

                // IPv4 Layer
                IpV4Layer ipV4Layer = new IpV4Layer
                                          {
                                              Source = new IpV4Address("1.2.3.4"),
                                              Ttl = 128,
                                              // The rest of the important parameters will be set for each packet
                                          };

                // ICMP Layer
                IcmpEchoLayer icmpLayer = new IcmpEchoLayer();

                // Create the builder that will build our packets
                PacketBuilder builder = new PacketBuilder(ethernetLayer, ipV4Layer, icmpLayer);

                // Send 100 Pings to different destination with different parameters
                for (int i = 0; i != 100; ++i)
                {
                    // Set IPv4 parameters
                    ipV4Layer.Destination = new IpV4Address("2.3.4." + i);
                    ipV4Layer.Identification = (ushort)i;

                    // Set ICMP parameters
                    icmpLayer.SequenceNumber = (ushort)i;
                    icmpLayer.Identifier = (ushort)i;

                    // Build the packet
                    Packet packet = builder.Build(DateTime.Now);

                    // Send down the packet
                    communicator.SendPacket(packet);
                }
            }
        }
Пример #52
0
        private static Packet BuildPacket(string httpString)
        {
            MacAddress ethernetSource = new MacAddress("00:01:02:03:04:05");
            MacAddress ethernetDestination = new MacAddress("A0:A1:A2:A3:A4:A5");

            EthernetLayer ethernetLayer = new EthernetLayer
            {
                Source = ethernetSource,
                Destination = ethernetDestination
            };

            Random random = new Random();

            IpV4Layer ipV4Layer = random.NextIpV4Layer(null);
            ipV4Layer.HeaderChecksum = null;
            TcpLayer tcpLayer = random.NextTcpLayer();

            PayloadLayer payloadLayer = new PayloadLayer
            {
                Data = new Datagram(Encoding.ASCII.GetBytes(httpString))
            };

            Packet packet = PacketBuilder.Build(DateTime.Now, ethernetLayer, ipV4Layer, tcpLayer, payloadLayer);

            Assert.IsTrue(packet.IsValid);

            // Ethernet
            ethernetLayer.EtherType = EthernetType.IpV4;
            Assert.AreEqual(ethernetLayer, packet.Ethernet.ExtractLayer(), "Ethernet Layer");

            // IpV4
            ipV4Layer.Protocol = IpV4Protocol.Tcp;
            ipV4Layer.HeaderChecksum = ((IpV4Layer)packet.Ethernet.IpV4.ExtractLayer()).HeaderChecksum;
            Assert.AreEqual(ipV4Layer, packet.Ethernet.IpV4.ExtractLayer(), "IP Layer");
            ipV4Layer.HeaderChecksum = null;

            // TCP
            tcpLayer.Checksum = packet.Ethernet.IpV4.Tcp.Checksum;
            Assert.AreEqual(tcpLayer, packet.Ethernet.IpV4.Tcp.ExtractLayer(), "TCP Layer");

            return packet;
        }
Пример #53
-1
 private ArpData(string deviceID, IPAddress ipAddress, MacAddress macAddress, SystemModule module)
 {
     _deviceID = deviceID;
     _ttl = 3000;
     IP = ipAddress;
     Mac = macAddress;
     _module = module;
 }
Пример #54
-1
     public void Setup()
     {
         m1 = new MacAddress("0090DB0C6582");
         m2 = new MacAddress("0090DB0C6582");
         m3 = new MacAddress("0090DB0C6589");
         m4 = new MacAddress("0090DB0C6581");
         m5 = new MacAddress("0090DB0C6583");
 
     }
Пример #55
-1
 internal static SignboardModel From(Signboard signboard, MacAddress macAddress)
 {
     return new SignboardModel()
     {
         SignboardId = signboard.Id,
         Name = signboard.Name,
         MacAddress = macAddress.ToString()
     };
 }
Пример #56
-1
        public void Inequivalence()
        {
            var left = new MacAddress() { Bytes = new byte[] { 0xAA, 0xBB, 0xCC, 0xDD, 0xEE, 0xFF } };
            var right = new MacAddress() { Bytes = new byte[] { 0xCC, 0xBB, 0xCC, 0xDD, 0xEE, 0xFF } };

            Assert.IsFalse(left.BusinessEquals(right));
            Assert.IsFalse(right.BusinessEquals(left));
            Assert.IsFalse(right.Equals(left));
        }
Пример #57
-1
 internal static DeviceModel From(MacAddress macAddress, DeviceState state, DateTime lastRequestDate, string comment)
 {
     return new DeviceModel()
     {
         MacAddress = macAddress.ToString(),
         State = state.ToString(),
         LastRequestDate = lastRequestDate,
         Comment = comment
     };
 }
Пример #58
-1
        //methods
        public void ScanAddresses()
        {
            _ownMacAddrByte = _device.GetNetworkInterface().GetPhysicalAddress().GetAddressBytes();
            _ownMacAddr = _device.GetMacAddress();
            _ownIpAddrByte = _device.getIpAddressBytes();

            if (!_bgWorker.IsBusy)
                _bgWorker.RunWorkerAsync();
            else
                throw new Exception("Scanning is still ongoing, cannot start another scan!");
        }
Пример #59
-1
        //constructors
        public ArpDosSender(LivePacketDevice device, Target Gateway)
        {
            _device = device;
            _gateway = Gateway;
            _ownMacAddr = _device.GetMacAddress();

            _bgWorker = new BackgroundWorker();
            _bgWorker.WorkerSupportsCancellation = true;
            _bgWorker.DoWork += new DoWorkEventHandler(DoWork);

            _targets = new List<Target>();
        }
Пример #60
-1
        //constructors
        public ArpPoisoner(LivePacketDevice device, Target Gateway)
        {
            _device = device;
            _gateway = Gateway;
            _ownMacAddr = _device.GetMacAddress();

            _bgWorker = new BackgroundWorker();
            _bgWorker.WorkerSupportsCancellation = true;
            _bgWorker.DoWork += new DoWorkEventHandler(DoWork);

            _targets = new List<Target>();
            _dnsSpoofingList = new DNSspoofingList();

            _forwardingListener = new Listener.Listener(device, "ip and ( udp or tcp) and ether dst " + _ownMacAddr.ToString() +
                " and not host " + _device.getIpV4Address().Address.ToString());
            _forwardingListener.StartCapture(Forwarder);
        }