Esempio n. 1
0
        /// <summary>
        /// Converts the string representation of an IPv4 address (1.2.3.4) to its IPv4 address equivalent.
        /// A return value indicates whether the conversion succeeded.
        /// </summary>
        /// <param name="value">A string containing the IPv4 address to convert (1.2.3.4).</param>
        /// <param name="result">
        /// When this method returns, contains the IPv4 address value equivalent of the IPv4 address contained in s, if the conversion succeeded,
        /// or zero IPv4 address if the conversion failed.
        /// The conversion fails if the s parameter is null or String.Empty or is not of the correct format. This parameter is passed uninitialized.
        /// </param>
        /// <returns>True iff parsing was successful.</returns>
        public static bool TryParse(string value, out IpV4Address result)
        {
            if (value == null)
            {
                result = Zero;
                return false;
            }

            string[] valuesStrings = value.Split('.');
            if (valuesStrings.Length != 4)
            {
                result = Zero;
                return false;
            }

            byte[] values = new byte[4];
            for (int i = 0; i != 4; ++i)
            {
                if (!byte.TryParse(valuesStrings[i], NumberStyles.None, CultureInfo.InvariantCulture, out values[i]))
                {
                    result = Zero;
                    return false;
                }
            }

            result = new IpV4Address(BitSequence.Merge(values[0], values[1], values[2], values[3]));
            return true;
        }
Esempio n. 2
0
 public ConnId(ushort lPort, IpV4Address rIp, ushort rPort, IpV4Protocol protocol)
 {
     this.lPort = lPort;
     this.rIp = rIp;
     this.rPort = rPort;
     this.protocol = protocol;
 }
Esempio n. 3
0
        private Packet BuildArpPacketRequest(IpV4Address targetIp)
        {
            EthernetLayer ethernetLayer =
            new EthernetLayer
            {
                Source = _ownMacAddr,
                Destination = _macBroadcastAddr,   //broadcast
                EtherType = EthernetType.None, // Will be filled automatically.
            };

            ArpLayer arpLayer =
                new ArpLayer
                {
                    ProtocolType = EthernetType.IpV4,
                    Operation = ArpOperation.Request,
                    SenderHardwareAddress = Array.AsReadOnly(_ownMacAddrByte), // self mac-address
                    SenderProtocolAddress = Array.AsReadOnly(_ownIpAddrByte), // self ip-address
                    TargetHardwareAddress = Array.AsReadOnly(_targetMacAddr), // Not Yet known
                    TargetProtocolAddress = Helper.IpAddressToBytes(targetIp) // ip we want to get the mac for
                };

            PacketBuilder builder = new PacketBuilder(ethernetLayer, arpLayer);

            return builder.Build(DateTime.Now);
        }
 private IpV6MobilityOptionLocalMobilityAnchorAddress(IpV6LocalMobilityAnchorAddressCode code, IpV4Address? localMobilityAnchorAddressIpV4,
                                                      IpV6Address? localMobilityAnchorAddressIpV6)
     : base(IpV6MobilityOptionType.LocalMobilityAnchorAddress)
 {
     Code = code;
     LocalMobilityAnchorAddressIpV6 = localMobilityAnchorAddressIpV6;
     LocalMobilityAnchorAddressIpV4 = localMobilityAnchorAddressIpV4;
 }
        /// <summary>
        /// Creates an instance from Prefix Length and Home Address.
        /// </summary>
        /// <param name="prefixLength">
        /// Indicates 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">
        /// Contains the IPv4 home address that is being requested.
        /// The value of 0.0.0.0 is used to request that the local mobility anchor perform the address allocation.
        /// </param>
        public IpV6MobilityOptionIpV4HomeAddressRequest(byte prefixLength, IpV4Address homeAddress)
            : base(IpV6MobilityOptionType.IpV4HomeAddressRequest)
        {
            if (prefixLength > MaxPrefixLength)
                throw new ArgumentOutOfRangeException("prefixLength", prefixLength,
                                                      string.Format(CultureInfo.InvariantCulture, "Max prefix length is {0}", MaxPrefixLength));

            PrefixLength = prefixLength;
            HomeAddress = homeAddress;
        }
        /// <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;
        }
        internal static bool Read(DataSegment data, out IpV4Address address)
        {
            if (data.Length != OptionDataLength)
            {
                address = IpV4Address.Zero;
                return false;
            }

            address = data.ReadIpV4Address(Offset.Address, Endianity.Big);
            return true;
        }
        /// <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;
        }
Esempio n. 9
0
        /// <summary>
        /// Tries to read the option from a buffer starting from the option value (after the type and length).
        /// </summary>
        /// <param name="buffer">The buffer to read the option from.</param>
        /// <param name="offset">The offset to the first byte to read the buffer. Will be incremented by the number of bytes read.</param>
        /// <param name="valueLength">The number of bytes the option value should take according to the length field that was already read.</param>
        /// <returns>On success - the complex option read. On failure - null.</returns>
        Option IOptionComplexFactory.CreateInstance(byte[] buffer, ref int offset, byte valueLength)
        {
            if (valueLength != OptionValueLength)
            {
                return(null);
            }

            ushort      identification      = buffer.ReadUShort(ref offset, Endianity.Big);
            ushort      outboundHopCount    = buffer.ReadUShort(ref offset, Endianity.Big);
            ushort      returnHopCount      = buffer.ReadUShort(ref offset, Endianity.Big);
            IpV4Address originatorIpAddress = buffer.ReadIpV4Address(ref offset, Endianity.Big);

            return(new IpV4OptionTraceRoute(identification, outboundHopCount, returnHopCount, originatorIpAddress));
        }
Esempio n. 10
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();
 }
Esempio n. 11
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);
        }
Esempio n. 12
0
        internal static IpV4Address CalculateDestination(IpV4Address currentDestination, IpV4Options options)
        {
            if (options == null)
            {
                return(currentDestination);
            }

            IpV4OptionRoute destinationControllerRouteOption =
                (IpV4OptionRoute)options.OptionsCollection.FirstOrDefault(option => option.OptionType == IpV4OptionType.LooseSourceRouting ||
                                                                          option.OptionType == IpV4OptionType.StrictSourceRouting);

            if (destinationControllerRouteOption != null)
            {
                ReadOnlyCollection <IpV4Address> route = destinationControllerRouteOption.Route;
                if (destinationControllerRouteOption.PointedAddressIndex < route.Count)
                {
                    return(route[route.Count - 1]);
                }
            }

            return(currentDestination);
        }
Esempio n. 13
0
        internal static bool TryRead(out IpV4Address[] addresses, out byte pointedAddressIndex, byte[] buffer, ref int offset, byte valueLength)
        {
            addresses           = (IpV4Address[])null;
            pointedAddressIndex = (byte)0;
            if ((int)valueLength < 1 || (int)valueLength % 4 != 1)
            {
                return(false);
            }
            byte num = buffer[offset++];

            if ((int)num % 4 != 0 || (int)num < 4)
            {
                return(false);
            }
            pointedAddressIndex = (byte)((int)num / 4 - 1);
            int length = (int)valueLength / 4;

            addresses = new IpV4Address[length];
            for (int index = 0; index != length; ++index)
            {
                addresses[index] = ByteArrayExtensions.ReadIpV4Address(buffer, ref offset, Endianity.Big);
            }
            return(true);
        }
 internal IpV6MobilityOptionIpV4Address(IpV6MobilityOptionType type, IpV4Address address) 
     : base(type)
 {
     Address = address;
 }
Esempio n. 15
0
 public bool Equals(IpV4Address other)
 {
     return((int)this.ToValue() == (int)other.ToValue());
 }
 /// <summary>
 /// Creates an instance from a care-of address.
 /// </summary>
 /// <param name="careOfAddress">
 /// Contains the mobile node's IPv4 care-of address.
 /// The IPv4 care-of address is used when the mobile node is located in an IPv4-only network.
 /// </param>
 public IpV6MobilityOptionIpV4CareOfAddress(IpV4Address careOfAddress)
     : base(IpV6MobilityOptionType.IpV4CareOfAddress, careOfAddress)
 {
 }
 /// <summary>
 /// Creates an instance from binding id, status, simulatneous home and foreign binding, priority and IPv4 care of address.
 /// </summary>
 /// <param name="bindingId">
 /// The BID that is assigned to the binding indicated by the care-of address in the Binding Update or the Binding Identifier mobility option.
 /// The value of zero is reserved and should not be used.
 /// </param>
 /// <param name="status">
 /// When the Binding Identifier mobility option is included in a Binding Acknowledgement,
 /// this field overwrites the Status field in the Binding Acknowledgement only for this BID.
 /// If this field is set to zero, the receiver ignores this field and uses the registration status stored in the Binding Acknowledgement message.
 /// The receiver must ignore this field if the Binding Identifier mobility option is not carried within either the Binding Acknowledgement
 /// or the Care-of Test messages.
 /// The possible status codes are the same as the status codes of the Binding Acknowledgement.
 /// This Status field is also used to carry error information related to the care-of address test in the Care-of Test message.
 /// </param>
 /// <param name="simultaneousHomeAndForeignBinding">
 /// Indicates that the mobile node registers multiple bindings to the home agent while it is attached to the home link.
 /// This flag is valid only for a Binding Update sent to the home agent.
 /// </param>
 /// <param name="priority">
 /// Places each BID to a relative priority (PRI) with other registered BIDs.
 /// Value '0' is reserved and must not be used.
 /// A lower number in this field indicates a higher priority, while BIDs with the same BID-PRI value have equal priority meaning that,
 /// the BID used is an implementation issue.
 /// This is consistent with current practice in packet classifiers.
 /// </param>
 /// <param name="careOfAddress">
 /// The IPv4 care-of address for the corresponding BID.
 /// </param>
 public IpV6MobilityOptionBindingIdentifier(ushort bindingId, IpV6BindingAcknowledgementStatus status, bool simultaneousHomeAndForeignBinding,
                                            byte priority, IpV4Address careOfAddress)
     : this(bindingId, status, simultaneousHomeAndForeignBinding, priority, careOfAddress, null)
 {
 }
 private IpV6MobilityOptionRedirect(IpV4Address? localMobilityAddressIpV4, IpV6Address? localMobilityAddressIpV6)
     : base(IpV6MobilityOptionType.Redirect)
 {
     LocalMobilityAddressIpV4 = localMobilityAddressIpV4;
     LocalMobilityAddressIpV6 = localMobilityAddressIpV6;
 }
Esempio n. 19
0
        void EventButtonStartClick(object sender, RoutedEventArgs e)
        {
            if (comboAdapter.SelectedIndex < 0)
            {
                MessageBox.Show("Adapter not selected");
                return;
            }

            if (iEndpoint == null)
            {
                MessageBox.Show("Endpoint not specified");
                return;
            }

            iMutex.WaitOne();
            iRunningDevice = iDevices[comboAdapter.SelectedIndex];
            iRunningEndpoint = iEndpoint;
            iRunningAddress = new IpV4Address(iRunningEndpoint.Address.ToString());
            ResetStats();

            buttonStart.IsEnabled = false;
            buttonStop.IsEnabled = true;
            iMutex.ReleaseMutex();
            iStart.Release();
        }
Esempio n. 20
0
 internal GreSourceRouteEntryIp(IpV4Address[] addresses, int nextAddressIndex)
     :this(addresses.AsReadOnly(), nextAddressIndex)
 {
 }
Esempio n. 21
0
 internal static void WriteVersion0Header(byte[] buffer, int offset,
                                          IgmpMessageType igmpMessageType, byte code, uint identifier, IpV4Address groupAddress, ulong accessKey)
 {
     buffer.Write(offset + Offset.MessageType, (byte)igmpMessageType);
     buffer.Write(offset + Offset.Code, code);
     buffer.Write(offset + Offset.Version0GroupAddress, groupAddress, Endianity.Big);
     buffer.Write(offset + Offset.Identifier, identifier, Endianity.Big);
     buffer.Write(offset + Offset.AccessKey, accessKey, Endianity.Big);
     WriteChecksum(buffer, offset, Version0HeaderLength);
 }
 public IpV4OptionTraceRoute(ushort identification, ushort outboundHopCount, ushort returnHopCount, IpV4Address originatorIpAddress)
     : base(IpV4OptionType.TraceRoute)
 {
     this._identification      = identification;
     this._outboundHopCount    = outboundHopCount;
     this._returnHopCount      = returnHopCount;
     this._originatorIpAddress = originatorIpAddress;
 }
Esempio n. 23
0
        private static ushort CalculateTransportChecksum(byte[] buffer, int offset, int headerLength, ushort transportLength, int transportChecksumOffset, bool isChecksumOptional, IpV4Address destination)
        {
            int  offsetAfterChecksum = offset + headerLength + transportChecksumOffset + 2;
            uint sum = Sum16Bits(buffer, offset + Offset.Source, IpV4Address.SizeOf) +
                       Sum16Bits(destination) +
                       buffer[offset + Offset.Protocol] + transportLength +
                       Sum16Bits(buffer, offset + headerLength, transportChecksumOffset) +
                       Sum16Bits(buffer, offsetAfterChecksum, transportLength - transportChecksumOffset - 2);

            ushort checksumResult = Sum16BitsToChecksum(sum);

            if (checksumResult == 0 && isChecksumOptional)
            {
                return(0xFFFF);
            }
            return(checksumResult);
        }
Esempio n. 24
0
        internal static void WriteTransportChecksum(byte[] buffer, int offset, int headerLength, ushort transportLength, int transportChecksumOffset, bool isChecksumOptional, ushort?checksum, IpV4Address destination)
        {
            ushort checksumValue =
                checksum == null
                    ? CalculateTransportChecksum(buffer, offset, headerLength, transportLength, transportChecksumOffset, isChecksumOptional, destination)
                    : checksum.Value;

            buffer.Write(offset + headerLength + transportChecksumOffset, checksumValue, Endianity.Big);
        }
Esempio n. 25
0
        internal static void WriteTransportChecksum(byte[] buffer, int offset, int headerLength, ushort transportLength, int transportChecksumOffset, bool isChecksumOptional, ushort?checksum, IpV4Address destination)
        {
            ushort?nullable = checksum;
            ushort num      = !(nullable.HasValue ? new int?((int)nullable.GetValueOrDefault()) : new int?()).HasValue ? IpV4Datagram.CalculateTransportChecksum(buffer, offset, headerLength, transportLength, transportChecksumOffset, isChecksumOptional, destination) : checksum.Value;

            ByteArrayExtensions.Write(buffer, offset + headerLength + transportChecksumOffset, num, Endianity.Big);
        }
Esempio n. 26
0
        private static ushort CalculateTransportChecksum(byte[] buffer, int offset, int headerLength, ushort transportLength, int transportChecksumOffset, bool isChecksumOptional, IpV4Address destination)
        {
            int    offset1 = offset + headerLength + transportChecksumOffset + 2;
            ushort num     = DataSegment.Sum16BitsToChecksum(DataSegment.Sum16Bits(buffer, offset + 12, 4) + DataSegment.Sum16Bits(destination) + (uint)buffer[offset + 9] + (uint)transportLength + DataSegment.Sum16Bits(buffer, offset + headerLength, transportChecksumOffset) + DataSegment.Sum16Bits(buffer, offset1, (int)transportLength - transportChecksumOffset - 2));

            if ((int)num == 0 && isChecksumOptional)
            {
                return(ushort.MaxValue);
            }
            return(num);
        }
 /// <summary>
 /// Create a timed address accroding to the given values.
 /// </summary>
 /// <param name="address">The address in the pair.</param>
 /// <param name="timeOfDay">The time passed since midnight UT.</param>
 public IpV4OptionTimedAddress(IpV4Address address, IpV4TimeOfDay timeOfDay)
 {
     _address   = address;
     _timeOfDay = timeOfDay;
 }
Esempio n. 28
0
        internal static void WriteQueryVersion3(byte[] buffer, int offset,
                                                TimeSpan maxResponseTime, IpV4Address groupAddress,
                                                bool isSuppressRouterSideProcessing, byte queryRobustnessVariable, TimeSpan queryInterval,
                                                IEnumerable<IpV4Address> sourceAddresses)
        {
            // MessageType
            buffer.Write(offset + Offset.MessageType, (byte)IgmpMessageType.MembershipQuery);

            // MaxResponseCode
            if (maxResponseTime < TimeSpan.Zero || maxResponseTime > MaxVersion3MaxResponseTime)
                throw new ArgumentOutOfRangeException("maxResponseTime", maxResponseTime, "must be in the range [" + TimeSpan.Zero + ", " + MaxVersion3MaxResponseTime + "]");
            double maxResponseTimeTenthOfASecond = maxResponseTime.TotalSeconds * 10;
            byte maxResponseCode = (byte)(maxResponseTimeTenthOfASecond < 128 ? maxResponseTimeTenthOfASecond : ValueToCode((int)maxResponseTimeTenthOfASecond));
            buffer.Write(offset + Offset.MaxResponseCode, maxResponseCode);

            // GroupAddress
            buffer.Write(offset + Offset.GroupAddress, groupAddress, Endianity.Big);

            // IsSuppressRouterSideProcessing and QueryRobustnessVariable
            if (queryRobustnessVariable > MaxQueryRobustnessVariable)
                throw new ArgumentOutOfRangeException("queryRobustnessVariable", queryRobustnessVariable, "must be in range [0, 7]");
            buffer.Write(offset + Offset.QueryRobustnessVariable, (byte)(queryRobustnessVariable | (isSuppressRouterSideProcessing ? 0x08 : 0x00)));

            // QueryIntervalCode
            if (queryInterval < TimeSpan.Zero || queryInterval > MaxQueryInterval)
                throw new ArgumentOutOfRangeException("queryInterval", maxResponseTime, "must be in the range [" + TimeSpan.Zero + ", " + MaxQueryInterval + "]");
            double queryIntervalTenthOfASecond = queryInterval.TotalSeconds;
            byte queryIntervalCode = (byte)(queryIntervalTenthOfASecond < 128 ? queryIntervalTenthOfASecond : ValueToCode((int)queryIntervalTenthOfASecond));
            buffer.Write(offset + Offset.QueryIntervalCode, queryIntervalCode);

            // SourceAddresses
            int numSourceAddresses = 0;
            foreach (IpV4Address sourceAddress in sourceAddresses)
            {
                buffer.Write(offset + Offset.SourceAddresses + IpV4Address.SizeOf * numSourceAddresses, sourceAddress, Endianity.Big);
                ++numSourceAddresses;
            }

            // NumberOfSources
            buffer.Write(offset + Offset.NumberOfSources, (ushort)numSourceAddresses, Endianity.Big);

            // Checksum
            WriteChecksum(buffer, offset, QueryVersion3HeaderLength + IpV4Address.SizeOf * numSourceAddresses);
        }
 /// <summary>
 /// Two addresses are equal if the have the exact same value.
 /// </summary>
 public bool Equals(IpV4Address other)
 {
     return(ToValue() == other.ToValue());
 }
Esempio n. 30
0
        internal static void WriteHeader(byte[] buffer, int offset, byte typeOfService, ushort identification, IpV4Fragmentation fragmentation, byte ttl, IpV4Protocol protocol, ushort?headerChecksum, IpV4Address source, IpV4Address destination, IpV4Options options, int payloadLength)
        {
            int length = 20 + options.BytesLength;

            buffer[offset]     = (byte)(64 + length / 4);
            buffer[offset + 1] = typeOfService;
            ByteArrayExtensions.Write(buffer, offset + 2, (ushort)(length + payloadLength), Endianity.Big);
            ByteArrayExtensions.Write(buffer, offset + 4, identification, Endianity.Big);
            fragmentation.Write(buffer, offset + 6);
            buffer[offset + 8] = ttl;
            buffer[offset + 9] = (byte)protocol;
            ByteArrayExtensions.Write(buffer, offset + 12, source, Endianity.Big);
            ByteArrayExtensions.Write(buffer, offset + 16, destination, Endianity.Big);
            options.Write(buffer, offset + 20);
            ushort?nullable = headerChecksum;
            ushort num      = !(nullable.HasValue ? new int?((int)nullable.GetValueOrDefault()) : new int?()).HasValue ? DataSegment.Sum16BitsToChecksum(DataSegment.Sum16Bits(buffer, offset, length)) : headerChecksum.Value;

            ByteArrayExtensions.Write(buffer, offset + 10, num, Endianity.Big);
        }
 /// <summary>
 /// Creates an instance from tagger id and identifier.
 /// </summary>
 /// <param name="taggerId">
 /// Used to differentiate multiple ingressing border gateways that may commonly apply the SMF_DPD option header to packets from a particular source.
 /// </param>
 /// <param name="identifier">
 /// DPD packet Identifier.
 /// When the TaggerId field is present, the Identifier can be considered a unique packet identifier 
 /// in the context of the TaggerId:srcAddr:dstAddr tuple.
 /// When the TaggerId field is not present, then it is assumed that the source applied the SMF_DPD option 
 /// and the Identifier can be considered unique in the context of the IPv6 packet header srcAddr:dstAddr tuple.
 /// </param>
 public IpV6OptionSimplifiedMulticastForwardingDuplicatePacketDetectionIpV4(IpV4Address taggerId, DataSegment identifier)
     : base(identifier)
 {
     TaggerId = taggerId;
 }
Esempio n. 32
0
        internal static void Write(byte[] buffer, ref int offset, IgmpRecordType recordType, Datagram auxiliaryData, IpV4Address multicastAddress, ReadOnlyCollection<IpV4Address> sourceAddresses)
        {
            buffer.Write(offset + Offset.RecordType, (byte)recordType);
            buffer.Write(offset + Offset.AuxiliaryDataLength, (byte)(auxiliaryData.Length / 4));
            int numSourceAddresses = sourceAddresses.Count;
            buffer.Write(offset + Offset.NumberOfSources, (ushort)numSourceAddresses, Endianity.Big);
            buffer.Write(offset + Offset.MulticastAddress, multicastAddress, Endianity.Big);
            for (int i = 0; i != numSourceAddresses; ++i)
                buffer.Write(offset + Offset.SourceAddresses + IpV4Address.SizeOf * i, sourceAddresses[i], Endianity.Big);

            offset += HeaderLength + numSourceAddresses * IpV4Address.SizeOf;
            buffer.Write(ref offset, auxiliaryData);
        }
 /// <summary>
 /// Creates an instance from an IPv4 local mobility address.
 /// </summary>
 /// <param name="localMobilityAddress">The IPv4 address of the r2LMA.</param>
 public IpV6MobilityOptionRedirect(IpV4Address localMobilityAddress)
     : this(localMobilityAddress, null)
 {
 }
 private IpV6MobilityOptionBindingIdentifier(ushort bindingId, IpV6BindingAcknowledgementStatus status, bool simultaneousHomeAndForeignBinding,
                                             byte priority, IpV4Address? ipV4CareOfAddress, IpV6Address? ipV6CareOfAddress)
     : base(IpV6MobilityOptionType.BindingIdentifier)
 {
     if (priority > MaxPriority)
         throw new ArgumentOutOfRangeException("priority", priority, string.Format(CultureInfo.InvariantCulture, "Must not exceed {0}", MaxPriority));
     BindingId = bindingId;
     Status = status;
     SimultaneousHomeAndForeignBinding = simultaneousHomeAndForeignBinding;
     Priority = priority;
     IpV4CareOfAddress = ipV4CareOfAddress;
     IpV6CareOfAddress = ipV6CareOfAddress;
 }
Esempio n. 35
0
 /// <summary>
 /// Writes the given value to the buffer using the given endianity and increments the offset by the number of bytes written.
 /// </summary>
 /// <param name="buffer">The buffer to write the value to.</param>
 /// <param name="offset">The offset in the buffer to start writing.</param>
 /// <param name="value">The value to write.</param>
 /// <param name="endianity">The endianity to use when converting the value to bytes.</param>
 public static void Write(this byte[] buffer, ref int offset, IpV4Address value, Endianity endianity)
 {
     buffer.Write(ref offset, value.ToValue(), endianity);
 }
Esempio n. 36
0
        internal static IpV4Address CalculateDestination(IpV4Address currentDestination, IpV4Options options)
        {
            if (options == null)
                return currentDestination;

            IpV4OptionRoute destinationControllerRouteOption =
                (IpV4OptionRoute)options.OptionsCollection.FirstOrDefault(option => option.OptionType == IpV4OptionType.LooseSourceRouting ||
                                                                                    option.OptionType == IpV4OptionType.StrictSourceRouting);
            if (destinationControllerRouteOption != null)
            {
                ReadOnlyCollection<IpV4Address> route = destinationControllerRouteOption.Route;
                if (destinationControllerRouteOption.PointedAddressIndex < route.Count)
                    return route[route.Count - 1];
            }

            return currentDestination;
        }
Esempio n. 37
0
        private static Packet BuildIcmpPacket(MacAddress SourceMac, MacAddress DestinationMac, IpV4Address SourceIp, IpV4Address CurrentDestination, string packetType)
        {
            EthernetLayer ethernetLayer =
                new EthernetLayer
                {
                    Source = SourceMac,
                    Destination = DestinationMac,
                    EtherType = EthernetType.None, // Will be filled automatically.
                };

            IpV4Layer ipV4Layer =
                new IpV4Layer
                {
                    //Source = new IpV4Address("1.2.3.4"),
                    //CurrentDestination = new IpV4Address("11.22.33.44"),
                    Source = SourceIp,
                    CurrentDestination = CurrentDestination,
                    Fragmentation = IpV4Fragmentation.None,
                    HeaderChecksum = null, // Will be filled automatically.
                    Identification = 123,
                    Options = IpV4Options.None,
                    Protocol = null, // Will be filled automatically.
                    Ttl = 100,
                    TypeOfService = 0,
                };

            IcmpEchoLayer icmpLayer = null;
            IcmpEchoReplyLayer icmpRLayer = null;

            PacketBuilder builder = null;

            if (packetType.Equals("REQUEST"))
            {
                Console.WriteLine("Request");
                icmpLayer =
                    new IcmpEchoLayer
                    {
                        Checksum = null, // Will be filled automatically.
                        Identifier = 456,
                        SequenceNumber = 800,
                    };
                builder = new PacketBuilder(ethernetLayer, ipV4Layer, icmpLayer);
            }
            else
            {
                Console.WriteLine("Reply");
                icmpRLayer =
                    new IcmpEchoReplyLayer
                    {
                        Checksum = null, // Will be filled automatically.
                        Identifier = 456,
                        SequenceNumber = 800,
                    };
                builder = new PacketBuilder(ethernetLayer, ipV4Layer, icmpRLayer);
            }

            return builder.Build(DateTime.Now);
        }
Esempio n. 38
0
        internal static void WriteHeader(byte[] buffer, int offset,
                                         byte typeOfService, ushort identification,
                                         IpV4Fragmentation fragmentation,
                                         byte ttl, IpV4Protocol protocol, ushort? headerChecksum,
                                         IpV4Address source, IpV4Address destination,
                                         IpV4Options options, int payloadLength)
        {
            int headerLength = HeaderMinimumLength + options.BytesLength;

            buffer[offset + Offset.VersionAndHeaderLength] = (byte)((DefaultVersion << 4) + headerLength / 4);
            buffer[offset + Offset.TypeOfService] = typeOfService;
            buffer.Write(offset + Offset.TotalLength, (ushort)(headerLength + payloadLength), Endianity.Big);
            buffer.Write(offset + Offset.Identification, identification, Endianity.Big);
            fragmentation.Write(buffer, offset + Offset.Fragmentation);
            buffer[offset + Offset.Ttl] = ttl;
            buffer[offset + Offset.Protocol] = (byte)protocol;

            buffer.Write(offset + Offset.Source, source, Endianity.Big);
            buffer.Write(offset + Offset.Destination, destination, Endianity.Big);
            options.Write(buffer, offset + Offset.Options);

            ushort headerChecksumValue =
                headerChecksum == null
                    ? Sum16BitsToChecksum(Sum16Bits(buffer, offset, headerLength))
                    : headerChecksum.Value;
            buffer.Write(offset + Offset.HeaderChecksum, headerChecksumValue, Endianity.Big);
        }
Esempio n. 39
0
        internal static void WriteHeader(byte[] buffer, int offset,
                                         IgmpMessageType igmpMessageType, TimeSpan maxResponseTime, IpV4Address groupAddress)
        {
            buffer.Write(offset + Offset.MessageType, (byte)igmpMessageType);

            double numTenthOfASecond = (maxResponseTime.TotalSeconds * 10);
            if (numTenthOfASecond >= 256 || numTenthOfASecond < 0)
                throw new ArgumentOutOfRangeException("maxResponseTime", maxResponseTime, "must be in the range [" + TimeSpan.Zero + ", " + TimeSpan.FromSeconds(255 * 0.1) + "]");
            buffer.Write(offset + Offset.MaxResponseCode, (byte)numTenthOfASecond);

            buffer.Write(offset + Offset.GroupAddress, groupAddress, Endianity.Big);

            WriteChecksum(buffer, offset, HeaderLength);
        }
Esempio n. 40
0
 internal static void WriteTransportChecksum(byte[] buffer, int offset, int headerLength, ushort transportLength, int transportChecksumOffset, bool isChecksumOptional, ushort? checksum, IpV4Address destination)
 {
     ushort checksumValue =
         checksum == null
             ? CalculateTransportChecksum(buffer, offset, headerLength, transportLength, transportChecksumOffset, isChecksumOptional, destination)
             : checksum.Value;
     buffer.Write(offset + headerLength + transportChecksumOffset, checksumValue, Endianity.Big);
 }
 internal static void WriteHeaderAdditional(byte[] buffer, int offset, IpV4Address addressMask)
 {
     buffer.Write(offset, addressMask, Endianity.Big);
 }
Esempio n. 42
0
        private static ushort CalculateTransportChecksum(byte[] buffer, int offset, int headerLength, ushort transportLength, int transportChecksumOffset, bool isChecksumOptional, IpV4Address destination)
        {
            int offsetAfterChecksum = offset + headerLength + transportChecksumOffset + sizeof(ushort);
            uint sum = Sum16Bits(buffer, offset + Offset.Source, IpV4Address.SizeOf) +
                       Sum16Bits(destination) +
                       buffer[offset + Offset.Protocol] + transportLength +
                       Sum16Bits(buffer, offset + headerLength, transportChecksumOffset) +
                       Sum16Bits(buffer, offsetAfterChecksum, transportLength - transportChecksumOffset - sizeof(ushort));

            ushort checksumResult = Sum16BitsToChecksum(sum);
            if (checksumResult == 0 && isChecksumOptional)
                return 0xFFFF;
            return checksumResult;
        }