/// <summary>
        /// Creates an instance from Prefix Length, Request Prefix and Home Address.
        /// </summary>
        /// <param name="prefixLength">
        /// The length of the prefix allocated to the mobile node.
        /// If only a single address is allocated, this field must be set to 32.
        /// In the first binding update requesting a prefix, the field contains the prefix length requested.
        /// However, in the following binding updates, this field must contain the length of the prefix allocated.
        /// A value of zero is invalid and must be considered an error.
        /// </param>
        /// <param name="requestPrefix">
        /// When true, indicates that the mobile node requests a mobile network prefix.
        /// This flag is only relevant for new requests, and must be ignored for binding refreshes.
        /// </param>
        /// <param name="homeAddress">
        /// The mobile node's IPv4 home address that should be defended by the home agent.
        /// This field could contain any unicast IPv4 address (public or private) that was assigned to the mobile node.
        /// The value 0.0.0.0 is used to request an IPv4 home address from the home agent.
        /// A mobile node may choose to use this option to request a prefix by setting the address to All Zeroes and setting the RequestPrefix flag.
        /// The mobile node could then form an IPv4 home address based on the allocated prefix.
        /// Alternatively, the mobile node may use two different options, one for requesting an address (static or dynamic) and another for requesting a
        /// </param>
        public IpV6MobilityOptionIpV4HomeAddress(byte prefixLength, bool requestPrefix, IpV4Address homeAddress)
            : base(IpV6MobilityOptionType.IpV4HomeAddress)
        {
            if (prefixLength > MaxPrefixLength)
            {
                throw new ArgumentOutOfRangeException("prefixLength", prefixLength,
                                                      string.Format(CultureInfo.InvariantCulture, "Exceeded maximum value {0}", MaxPrefixLength));
            }

            PrefixLength  = prefixLength;
            RequestPrefix = requestPrefix;
            HomeAddress   = homeAddress;
        }
 private void ReactOnScanner(IpV4Address address)
 {
     try
     {
         this.options.Reacting.React(address);
     }
     catch (InvalidOperationException exception)
     {
         Console.WriteLine(exception.Message);
         Console.WriteLine("Now and then all scanners will be ignored...");
         this.options.Reacting = new IgnoreScanningReaction();
     }
 }
Exemple #3
0
 public void Add(IpV4Address IP, MacAddress Mac)
 {
     if (_arp_table.ContainsKey(IP))
     {
         _arp_table[IP] = Mac;
         VirtualNetwork.Instance.PostTraceMessage("ARP table item update: " + IP.ToString() + " = " + Mac.ToString());
     }
     else
     {
         _arp_table.Add(IP, Mac);
         VirtualNetwork.Instance.PostTraceMessage("ARP table item add: " + IP.ToString() + " = " + Mac.ToString());
     }
 }
Exemple #4
0
        internal override IpV6MobilityOption CreateInstance(DataSegment data)
        {
            if (data.Length != OptionDataLength)
            {
                return(null);
            }

            IpV6IpV4HomeAddressReplyStatus status = (IpV6IpV4HomeAddressReplyStatus)data[Offset.Status];
            byte        prefixLength = (byte)((data[Offset.PrefixLength] & Mask.PrefixLength) >> Shift.PrefixLength);
            IpV4Address homeAddress  = data.ReadIpV4Address(Offset.HomeAddress, Endianity.Big);

            return(new IpV6MobilityOptionIpV4HomeAddressReply(status, prefixLength, homeAddress));
        }
        /// <summary>
        /// Creates an instance from status, Prefix Length and Home Address.
        /// </summary>
        /// <param name="status">
        /// Indicates success or failure for the IPv4 home address binding.
        /// Values from 0 to 127 indicate success.
        /// Higher values indicate failure.
        /// </param>
        /// <param name="prefixLength">
        /// The prefix length of the address allocated.
        /// This field is only valid in case of success and must be set to zero and ignored in case of failure.
        /// This field overrides what the mobile node requested (if not equal to the requested length).
        /// </param>
        /// <param name="homeAddress">
        /// The IPv4 home address that the home agent will use in the binding cache entry.
        /// This could be a public or private address.
        /// This field must contain the mobile node's IPv4 home address.
        /// If the address were dynamically allocated, the home agent will add the address to inform the mobile node.
        /// Otherwise, if the address is statically allocated to the mobile node, the home agent will copy it from the binding update message.
        /// </param>
        public IpV6MobilityOptionIpV4AddressAcknowledgement(IpV6AddressAcknowledgementStatus status, byte prefixLength, IpV4Address homeAddress)
            : base(IpV6MobilityOptionType.IpV4AddressAcknowledgement)
        {
            if (prefixLength > MaxPrefixLength)
            {
                throw new ArgumentOutOfRangeException("prefixLength", prefixLength,
                                                      string.Format(CultureInfo.InvariantCulture, "Exceeded maximum value {0}", MaxPrefixLength));
            }

            Status       = status;
            PrefixLength = prefixLength;
            HomeAddress  = homeAddress;
        }
Exemple #6
0
        /// <summary>
        /// Creates an instance from status, Prefix Length and Home Address.
        /// </summary>
        /// <param name="status">
        /// Indicates success or failure for the IPv4 home address assignment.
        /// Values from 0 to 127 indicate success.
        /// Higher values (128 to 255) indicate failure.
        /// </param>
        /// <param name="prefixLength">
        /// Used to carry the prefix length of the mobile node's IPv4 home network corresponding to the IPv4 home address contained in the option.
        /// </param>
        /// <param name="homeAddress">
        /// Used to carry the IPv4 home address assigned to the mobile node.
        /// </param>
        public IpV6MobilityOptionIpV4HomeAddressReply(IpV6IpV4HomeAddressReplyStatus status, byte prefixLength, IpV4Address homeAddress)
            : base(IpV6MobilityOptionType.IpV4HomeAddressReply)
        {
            if (prefixLength > MaxPrefixLength)
            {
                throw new ArgumentOutOfRangeException("prefixLength", prefixLength,
                                                      string.Format(CultureInfo.InvariantCulture, "Max prefix length is {0}", MaxPrefixLength));
            }

            Status       = status;
            PrefixLength = prefixLength;
            HomeAddress  = homeAddress;
        }
        internal override DnsResourceData CreateInstance(DataSegment data)
        {
            if (data.Length < ConstantPartLength)
            {
                return(null);
            }

            IpV4Address  address  = data.ReadIpV4Address(Offset.Address, Endianity.Big);
            IpV4Protocol protocol = (IpV4Protocol)data[Offset.Protocol];
            DataSegment  bitmap   = data.Subsegment(Offset.Bitmap, data.Length - Offset.Bitmap);

            return(new DnsResourceDataWellKnownService(address, protocol, bitmap));
        }
        internal override IpV6MobilityOption CreateInstance(DataSegment data)
        {
            if (data.Length != OptionDataLength)
            {
                return(null);
            }

            byte        prefixLength  = (byte)((data[Offset.PrefixLength] & Mask.PrefixLength) >> Shift.PrefixLength);
            bool        requestPrefix = data.ReadBool(Offset.RequestPrefix, Mask.RequestPrefix);
            IpV4Address homeAddress   = data.ReadIpV4Address(Offset.HomeAddress, Endianity.Big);

            return(new IpV6MobilityOptionIpV4HomeAddress(prefixLength, requestPrefix, homeAddress));
        }
Exemple #9
0
        public void Constructor_Should_ConvertMaskIntoAppropiateMask_When_MaskInFourthOctet()
        {
            // Arrange
            var mask     = 27;
            var address  = new IpV4Address(192, 168, 0, 1);
            var expected = "255.255.255.224";

            // Act
            var network = new IpV4Network(address, mask);

            // Assert
            Assert.Equal(expected, network.Netmask.ToString());
        }
Exemple #10
0
        public Packet CreateDnsReply(EthernetDatagram etherpacket, IpV4Address newAddress)
        {
            var ipPacket  = etherpacket.IpV4;
            var udpPacket = ipPacket.Udp;
            var dnsPacket = udpPacket.Dns;

            if (!dnsPacket.IsQuery)
            {
                throw new Exception("Packet should be a dns query!");
            }

            EthernetLayer ethernetLayer = new EthernetLayer
            {
                Source      = etherpacket.Destination,
                Destination = etherpacket.Source,
            };

            IpV4Layer ipLayer = new IpV4Layer
            {
                Source             = ipPacket.Destination,
                CurrentDestination = ipPacket.Source,
            };

            UdpLayer udpLayer = new UdpLayer
            {
                SourcePort      = udpPacket.DestinationPort,
                DestinationPort = udpPacket.SourcePort
            };


            DnsResourceData       resourceData   = new DnsResourceDataIpV4(newAddress);
            DnsDataResourceRecord resourceRecord = new DnsDataResourceRecord(dnsPacket.Queries[0].DomainName,
                                                                             dnsPacket.Queries[0].DnsType,
                                                                             dnsPacket.Queries[0].DnsClass,
                                                                             60,
                                                                             resourceData);

            DnsLayer dnsLayer = new DnsLayer
            {
                Queries    = dnsPacket.Queries,
                IsQuery    = false,
                IsResponse = true,
                Id         = dnsPacket.Id,
                Answers    = new[] { resourceRecord }
            };

            PacketBuilder builder = new PacketBuilder(ethernetLayer, ipLayer, udpLayer, dnsLayer);

            return(builder.Build(DateTime.Now));
        }
Exemple #11
0
 public TapWorker(Guid guid, string name, string mac, string ip, string gateway)
 {
     Guid = guid;
     Name = name;
     ifHardwareAddressString  = mac;
     ifProtocolAddressString  = ip;
     ownProtocolAddressString = gateway;
     ifHardwareAddress        = new MacAddress(ifHardwareAddressString);
     ifProtocolAddress        = new IpV4Address(ifProtocolAddressString);
     ownProtocolAddress       = new IpV4Address(ownProtocolAddressString);
     ifHardwareAddressByte    = ifHardwareAddressString.Split(':').Select(s => Convert.ToByte(s, 16)).ToArray();
     ifProtocolAddressByte    = ifProtocolAddressString.Split('.').Select(byte.Parse).ToArray();
     ownProtocolAddressByte   = ownProtocolAddressString.Split('.').Select(byte.Parse).ToArray();
 }
Exemple #12
0
        private void CreateFakeAddresses(int count)
        {
            FakeIpV4Addresses = new List <IpV4Address>();
            var ipAddress = ParseIpAddress(SourceIpv4);

            while (FakeIpV4Addresses.Count != count)
            {
                var ipAddressFaked = new IpV4Address($"{ipAddress[0]}.{ipAddress[1]}.{ipAddress[2]}.{_rand.Next(FakeIpAddressMin, FakeIpAddressMax)}");
                if (!FakeIpV4Addresses.Contains(ipAddressFaked) && !ipAddressFaked.ToString().Equals(SourceIpv4) && !ipAddressFaked.ToString().Equals(DestinationIpV4))
                {
                    FakeIpV4Addresses.Add(ipAddressFaked);
                }
            }
        }
Exemple #13
0
        /// <summary>
        /// Creates an address from an address string ("2001:0db8:0::22:1.2.3.4").
        /// </summary>
        public IpV6Address(string value)
        {
            if (value == null)
            {
                throw new ArgumentNullException("value");
            }

            string cannonizedValue = value;

            // Handle ...:1.2.3.4
            int lastColonIndex = cannonizedValue.LastIndexOf(':');

            if (lastColonIndex == -1)
            {
                throw new ArgumentException("Invalid IPv6 address format " + value);
            }

            string lastPart = value.Substring(lastColonIndex + 1, cannonizedValue.Length - lastColonIndex - 1);

            if (lastPart.IndexOf('.') != -1)
            {
                uint lastPartValue = new IpV4Address(lastPart).ToValue();
                cannonizedValue = cannonizedValue.Substring(0, lastColonIndex + 1) +
                                  (lastPartValue >> 16).ToString("x", CultureInfo.InvariantCulture) + ":" + (lastPartValue & 0x0000FFFF).ToString("x", CultureInfo.InvariantCulture);
            }

            // Handle ...::...
            int doubleColonIndex = cannonizedValue.IndexOf("::", StringComparison.Ordinal);

            if (doubleColonIndex != -1)
            {
                int numMissingColons = 7 - cannonizedValue.Count(':');
                if (numMissingColons < 0)
                {
                    throw new ArgumentException("Invalid IPv6 address format " + value);
                }
                cannonizedValue = cannonizedValue.Substring(0, doubleColonIndex + 2) +
                                  new string(':', numMissingColons) +
                                  cannonizedValue.Substring(doubleColonIndex + 2);
            }

            IEnumerable <ushort> values =
                cannonizedValue.Split(':').Select(part => string.IsNullOrEmpty(part) ? (ushort)0 : ushort.Parse(part, NumberStyles.HexNumber, CultureInfo.InvariantCulture));

            ulong mostSignificant  = values.Take(4).Aggregate((ulong)0, (sum, element) => (sum << 16) + element);
            ulong leastSignificant = values.Skip(4).Take(4).Aggregate((ulong)0, (sum, element) => (sum << 16) + element);

            _value = new UInt128(mostSignificant, leastSignificant);
        }
Exemple #14
0
 public static IpV4Layer BuildIpV4Frame(IpV4Address victimsIP, IpV4Address destinationIp, byte ttl)
 {
     return(new IpV4Layer()
     {
         Source = victimsIP,
         CurrentDestination = destinationIp,
         Fragmentation = IpV4Fragmentation.None,
         HeaderChecksum = null,      // automatically figured out
         Identification = 123,       // made this up
         Options = IpV4Options.None, // figure it out yourself.
         Protocol = null,            // will figure itself out.
         Ttl = ttl,
         TypeOfService = 0
     });
 }
 public IgmpGroupRecord(IgmpRecordType recordType, IpV4Address multicastAddress, ReadOnlyCollection <IpV4Address> sourceAddresses, Datagram auxiliaryData)
 {
     if (auxiliaryData == null)
     {
         throw new ArgumentNullException("auxiliaryData");
     }
     if (auxiliaryData.Length % 4 != 0)
     {
         throw new ArgumentException("Auxiliary data length must divide by 4 and can't be " + (object)auxiliaryData.Length, "auxiliaryData");
     }
     this.RecordType       = recordType;
     this.MulticastAddress = multicastAddress;
     this.SourceAddresses  = sourceAddresses;
     this.AuxiliaryData    = auxiliaryData;
 }
Exemple #16
0
        public void SendIcmpEcho(IpV4Address TargetIP, MacAddress TargetMac, ushort SequenceNumber)
        {
            EthernetLayer ethernetLayer =
                new EthernetLayer
            {
                Source      = _adapter.MAC,
                Destination = TargetMac,
                EtherType   = EthernetType.None,   // Will be filled automatically.
            };

            VLanTaggedFrameLayer vlanLayer =
                new VLanTaggedFrameLayer
            {
                PriorityCodePoint        = ClassOfService.BestEffort,
                CanonicalFormatIndicator = false,
                VLanIdentifier           = _adapter.VLAN,
                EtherType = EthernetType.None,
            };

            IpV4Layer ipV4Layer =
                new IpV4Layer
            {
                Source             = _adapter.IP,
                CurrentDestination = TargetIP,
                Fragmentation      = IpV4Fragmentation.None,
                HeaderChecksum     = null, // Will be filled automatically.
                Identification     = SequenceNumber,
                Options            = IpV4Options.None,
                Protocol           = null, // Will be filled automatically.
                Ttl           = 100,
                TypeOfService = 0,
            };

            IcmpEchoLayer icmpLayer = new IcmpEchoLayer
            {
                SequenceNumber = SequenceNumber,
                Identifier     = SequenceNumber,
            };

            if (_adapter.VLAN > 1)
            {
                VirtualNetwork.Instance.SendPacket(PacketBuilder.Build(DateTime.Now, ethernetLayer, vlanLayer, ipV4Layer, icmpLayer));
            }
            else
            {
                VirtualNetwork.Instance.SendPacket(PacketBuilder.Build(DateTime.Now, ethernetLayer, ipV4Layer, icmpLayer));
            }
        }
Exemple #17
0
        private INetFwRule SetupNetFwRule(IpV4Address scanner)
        {
            Guid       clsid      = new Guid(BlockIPScanningReaction.guidRWRule);
            Type       typeFWRule = Type.GetTypeFromCLSID(clsid);
            INetFwRule newRule    = (INetFwRule)Activator.CreateInstance(typeFWRule);

            newRule.Name            = "AntiScan_Rule";
            newRule.Description     = String.Format("Block inbound traffic from {0}", scanner.ToString());
            newRule.Protocol        = (int)NET_FW_IP_PROTOCOL_.NET_FW_IP_PROTOCOL_ANY;
            newRule.RemoteAddresses = scanner.ToString();
            newRule.Direction       = NET_FW_RULE_DIRECTION_.NET_FW_RULE_DIR_IN;
            newRule.Enabled         = true;
            newRule.Grouping        = "AntiScanning rule added from clr...";
            newRule.Action          = NET_FW_ACTION_.NET_FW_ACTION_BLOCK;
            return(newRule);
        }
Exemple #18
0
 public void Remove(IpV4Address IP)
 {
     if (IP != null && !IP.Equals(IpV4Address.Zero))
     {
         if (_arp_table.ContainsKey(IP))
         {
             _arp_table.Remove(IP);
             VirtualNetwork.Instance.PostTraceMessage("ARP table item remove: " + IP.ToString());
         }
     }
     else
     {
         _arp_table.Clear();
         VirtualNetwork.Instance.PostTraceMessage("ARP table clear");
     }
 }
Exemple #19
0
        public static ReadOnlyCollection <byte> ToBytes(this IpV4Address ip)
        {
            var hexValues = ip.ToString().Split('.');

            if (hexValues.Length != 4)
            {
                throw new InvalidCastException($"{ip} is not a valid ip address");
            }

            var ipBytes = new byte[4];

            for (int i = 0; i < hexValues.Length; i++)
            {
                ipBytes[i] = Convert.ToByte(hexValues[i]);
            }
            return(ipBytes.AsReadOnly());
        }
Exemple #20
0
        private bool ExistsBlockingRuleFor(IpV4Address scanner, INetFwPolicy2 fwPolicy)
        {
            INetFwRules rules = fwPolicy.Rules;

            foreach (INetFwRule rule in rules)
            {
                bool   isAppMadeRule    = rule.Name == "AntiScan_Rule";
                string addresses        = rule.RemoteAddresses;
                int    slashPos         = addresses.IndexOf('/');
                string address          = slashPos > 0 ? addresses.Substring(0, slashPos) : String.Empty;
                bool   isScannerBlocked = address == scanner.ToString();
                if (isAppMadeRule && isScannerBlocked)
                {
                    return(true);
                }
            }
            return(false);
        }
        private static bool TryReadEntry(byte[] buffer, int payloadOffset, int payloadLength, GreSourceRouteEntryAddressFamily addressFamily, int offsetInPayload, out GreSourceRouteEntry entry)
        {
            entry = null;
            switch (addressFamily)
            {
            case GreSourceRouteEntryAddressFamily.IpSourceRoute:
                if (offsetInPayload % IpV4Address.SizeOf != 0 || payloadLength % IpV4Address.SizeOf != 0)
                {
                    return(false);
                }

                int           numAddresses = payloadLength / IpV4Address.SizeOf;
                IpV4Address[] addresses    = new IpV4Address[numAddresses];
                for (int i = 0; i != numAddresses; ++i)
                {
                    addresses[i] = buffer.ReadIpV4Address(payloadOffset + i * IpV4Address.SizeOf, Endianity.Big);
                }

                entry = new GreSourceRouteEntryIp(addresses, offsetInPayload / IpV4Address.SizeOf);
                return(true);

            case GreSourceRouteEntryAddressFamily.AsSourceRoute:
                if (offsetInPayload % sizeof(ushort) != 0 || payloadLength % sizeof(ushort) != 0)
                {
                    return(false);
                }

                int      numAsNumbers = payloadLength / sizeof(ushort);
                ushort[] asNumbers    = new ushort[numAsNumbers];
                for (int i = 0; i != numAsNumbers; ++i)
                {
                    asNumbers[i] = buffer.ReadUShort(payloadOffset + i * sizeof(ushort), Endianity.Big);
                }

                entry = new GreSourceRouteEntryAs(asNumbers, offsetInPayload / sizeof(ushort));
                return(true);

            default:
                Datagram data = new Datagram(buffer, payloadOffset, payloadLength);
                entry = new GreSourceRouteEntryUnknown(addressFamily, data, offsetInPayload);
                return(true);
            }
        }
        public Telnet(string ConfigString, string FriendlyName) : base(ConfigString, FriendlyName)
        {
            // L2Telnet:IP=192.168.1.1, Port=23, Adapter=SOCKET_1, ConfigFile=Config\\TEST_NET.network
            if (VirtualNetwork.Instance == null)
            {
                string NetworkConfigFile = Config["ConfigFile"];
                VirtualNetwork.Load(NetworkConfigFile);
                VirtualNetwork.Instance.Start();
            }
            else
            {
                if (!VirtualNetwork.Instance.IsRunning)
                {
                    VirtualNetwork.Instance.Start();
                }
            }

            Adapter = VirtualNetwork.Instance.GetAdapterByName(Config["Adapter"]);
            Adapter.BoardcastLocalAddress();
            this._service     = Adapter.TcpService;
            this._adapter     = Adapter;
            this._local_port  = this._service.GetAvailableLocalPort();
            this._remote_ip   = new IpV4Address(Config["IP"]);
            this._remote_port = ushort.Parse(Config["Port"]);

            if (Config.ContainsKey("MAC") && !string.IsNullOrEmpty(Config["MAC"]))
            {
                this._remote_mac = new MacAddress(Config["MAC"]);
            }

            if (Config.ContainsKey("RESPONSE_TELNET_CTRL") && !string.IsNullOrEmpty(Config["RESPONSE_TELNET_CTRL"]))
            {
                this._response_telnet_ctrl = bool.Parse(Config["RESPONSE_TELNET_CTRL"]);
            }

            if (Config.ContainsKey("SEND_GRATUITUS") && !string.IsNullOrEmpty(Config["SEND_GRATUITUS"]))
            {
                this._send_gratuitus_when_no_response = bool.Parse(Config["SEND_GRATUITUS"]);
            }

            _current_state = TCP_STATE.CLOSED;
            this._service.AddSession(this);
        }
Exemple #23
0
        public void IpV4AddressWithBufferTest()
        {
            Random random = new Random();

            for (int i = 0; i != 1000; ++i)
            {
                IpV4Address address = random.NextIpV4Address();

                byte[] buffer = new byte[IpV4Address.SizeOf];

                buffer.Write(0, address, Endianity.Big);
                Assert.AreEqual(address, buffer.ReadIpV4Address(0, Endianity.Big));
                Assert.AreNotEqual(address, buffer.ReadIpV4Address(0, Endianity.Small));

                buffer.Write(0, address, Endianity.Small);
                Assert.AreEqual(address, buffer.ReadIpV4Address(0, Endianity.Small));
                Assert.AreNotEqual(address, buffer.ReadIpV4Address(0, Endianity.Big));
            }
        }
        private Host ParseHostInformation()
        {
            var errorMessage = new Action <string, string>((title, msg) => MessageBox.Show(msg, title, MessageBoxButtons.OK, MessageBoxIcon.Error));

            IpV4Address ip;
            MacAddress  mac;

            try
            {
                ip = new IpV4Address(tbIpAddress.Text);
            }
            catch (Exception)
            {
                errorMessage("Value Error", "Invalid IP address.");
                return(null);
            }

            try
            {
                mac = new MacAddress(tbMacAddress.Text);
            }
            catch (Exception)
            {
                errorMessage("Value Error", "Invalid MAC address");
                return(null);
            }

            var host = new Host(ip, mac)
            {
                HostName = tbHostName.Text
            };

            if (_hosts.Contains(host))
            {
                errorMessage("Duplicate", "Specified host does already exist.");
                return(null);
            }
            else
            {
                return(host);
            }
        }
Exemple #25
0
        public IpV6Address(string value)
        {
            if (value == null)
            {
                throw new ArgumentNullException("value");
            }
            string str1 = value;
            int    num1 = str1.LastIndexOf(':');

            if (num1 == -1)
            {
                throw new ArgumentException("Invalid IPv6 address format " + value);
            }
            string str2 = value.Substring(num1 + 1, str1.Length - num1 - 1);

            if (str2.IndexOf('.') != -1)
            {
                uint num2 = new IpV4Address(str2).ToValue();
                str1 = str1.Substring(0, num1 + 1) + (num2 >> 16).ToString("x", (IFormatProvider)CultureInfo.InvariantCulture) + ":" + (num2 & (uint)ushort.MaxValue).ToString("x", (IFormatProvider)CultureInfo.InvariantCulture);
            }
            int num3 = str1.IndexOf("::", StringComparison.Ordinal);

            if (num3 != -1)
            {
                int count = 7 - IEnumerableExtensions.Count <char>((IEnumerable <char>)str1, ':');
                if (count < 0)
                {
                    throw new ArgumentException("Invalid IPv6 address format " + value);
                }
                str1 = str1.Substring(0, num3 + 2) + new string(':', count) + str1.Substring(num3 + 2);
            }
            IEnumerable <ushort> source = Enumerable.Select <string, ushort>((IEnumerable <string>)str1.Split(':'), (Func <string, ushort>)(part =>
            {
                if (!string.IsNullOrEmpty(part))
                {
                    return(ushort.Parse(part, NumberStyles.HexNumber, (IFormatProvider)CultureInfo.InvariantCulture));
                }
                return((ushort)0);
            }));

            this._value = new UInt128(Enumerable.Aggregate <ushort, ulong>(Enumerable.Take <ushort>(source, 4), 0UL, (Func <ulong, ushort, ulong>)((sum, element) => (sum << 16) + (ulong)element)), Enumerable.Aggregate <ushort, ulong>(Enumerable.Take <ushort>(Enumerable.Skip <ushort>(source, 4), 4), 0UL, (Func <ulong, ushort, ulong>)((sum, element) => (sum << 16) + (ulong)element)));
        }
Exemple #26
0
 public PhysicalWorker(Guid guid, string name, string ifMac, string ifIp, string ifMask, string gatewayMac, string gatewayIp)
 {
     Guid = guid;
     Name = name;
     ifHardwareAddressString      = ifMac;
     ifProtocolAddressString      = ifIp;
     ifProtocolMaskString         = ifMask;
     gatewayHardwareAddressString = gatewayMac;
     gatewayProtocolAddressString = gatewayIp;
     ifHardwareAddress            = new MacAddress(ifHardwareAddressString);
     ifProtocolAddress            = new IpV4Address(ifProtocolAddressString);
     ifProtocolMask             = new IpV4Address(ifProtocolMaskString);
     gatewayHardwareAddress     = new MacAddress(gatewayHardwareAddressString);
     gatewayProtocolAddress     = new IpV4Address(gatewayProtocolAddressString);
     ifHardwareAddressByte      = ifHardwareAddressString.Split(':').Select(s => Convert.ToByte(s, 16)).ToArray();
     ifProtocolAddressByte      = ifProtocolAddressString.Split('.').Select(byte.Parse).ToArray();
     ifProtocolMaskByte         = ifProtocolMaskString.Split('.').Select(byte.Parse).ToArray();
     gatewayHardwareAddressByte = gatewayHardwareAddressString.Split(':').Select(s => Convert.ToByte(s, 16)).ToArray();
     gatewayProtocolAddressByte = gatewayProtocolAddressString.Split('.').Select(byte.Parse).ToArray();
 }
Exemple #27
0
        public void React(IpV4Address scanner)
        {
            try
            {
                INetFwPolicy2 fwPolicy = GetNetFwPolicy();
                if (ExistsBlockingRuleFor(scanner, fwPolicy))
                {
                    return;
                }

                Console.WriteLine("Adding firewall rule...");
                INetFwRule newRule = SetupNetFwRule(scanner);
                newRule.Profiles = fwPolicy.CurrentProfileTypes;
                fwPolicy.Rules.Add(newRule);
            }
            catch (UnauthorizedAccessException exception)
            {
                throw new InvalidOperationException("You don't have rights for changing firewall rules without administrator rights.", exception);
            }
        }
Exemple #28
0
        private static void Sationsip(string mac)
        {
            Console.WriteLine("neue ip: ");
            var         value0 = Console.ReadLine();
            IpV4Address ip4    = new IpV4Address(value0);
            var         i      = ip4.ToValue().ToString("X");
            var         g      = ip4.ToValue().ToString("X");

            Console.WriteLine("neue gateway: " + value0);

            Console.WriteLine("neue subnetz: ");
            var         value1    = Console.ReadLine();
            IpV4Address ipsubnetz = new IpV4Address(value1);
            var         s         = ipsubnetz.ToValue().ToString("X");

            var t = new Thread(() => { Recive(30, DefaultPacketHandler); });

            t.Start();
            SendSetRequest(mac, "0102", i + s + g);
        }
        public Connection(IpV4Address source, ushort sourcePort, IpV4Address destination, ushort destinationPort,
                          Packet packet, EventHandler timerHandler, EventHandler establishedHandler, EventHandler closeWaitHandler)
        {
            this.source          = source;
            this.sourcePort      = sourcePort;
            this.destination     = destination;
            this.destinationPort = destinationPort;

            startTime = DateTime.MinValue;
            endTime   = startTime;

            connectionClosedEvent      += timerHandler;
            connectionEstablishedEvent += establishedHandler;
            connectionCloseAttempEvent += closeWaitHandler;

            timer = new Timer(CallEventHandler, connectionClosedEvent, timeWait, -1);

            packets       = new List <Packet>();
            directPackets = new List <Packet>();
            backPackets   = new List <Packet>();
            packets.Add(packet);

            IpV4Datagram ip = packet.Ethernet.IpV4;

            protocol = ip.Protocol;

            TcpDatagram tcp = packet.GetDatagram() as TcpDatagram;

            isTcp = packet.GetDatagram() is TcpDatagram;

            if (tcp != null)
            {
                ++synCount;
                directPackets.Add(packet);
            }
            else
            {
                directPackets.Add(packet);
                isEstablished = true;
            }
        }
Exemple #30
0
        public void TryParseTest()
        {
            IpV4Address actual;

            Assert.IsTrue(IpV4Address.TryParse("1.2.3.4", out actual));
            Assert.AreEqual(new IpV4Address("1.2.3.4"), actual);

            Assert.IsFalse(IpV4Address.TryParse(null, out actual));
            Assert.IsFalse(IpV4Address.TryParse("1", out actual));
            Assert.IsFalse(IpV4Address.TryParse("1.", out actual));
            Assert.IsFalse(IpV4Address.TryParse("1.2", out actual));
            Assert.IsFalse(IpV4Address.TryParse("1.2.", out actual));
            Assert.IsFalse(IpV4Address.TryParse("1.2.3", out actual));
            Assert.IsFalse(IpV4Address.TryParse("1.2.3.", out actual));
            Assert.IsFalse(IpV4Address.TryParse("1.2.3.a", out actual));
            Assert.IsFalse(IpV4Address.TryParse("a.2.3.4", out actual));
            Assert.IsFalse(IpV4Address.TryParse("1.a.3.4", out actual));
            Assert.IsFalse(IpV4Address.TryParse("1.2.a.4", out actual));
            Assert.IsFalse(IpV4Address.TryParse("1.2.3.a", out actual));
            Assert.IsFalse(IpV4Address.TryParse("256.2.3.4", out actual));
        }