コード例 #1
0
ファイル: ArpEntry.cs プロジェクト: smiley22/Network.Sim
		/// <summary>
		/// Initializes a new instance of the ArpEntry class using the specified
		/// values.
		/// </summary>
		/// <param name="ipAddress">The IPv4 address to initialize this entry
		/// with.</param>
		/// <param name="macAddress">The MAC-48 address to initialize this entry
		/// with.</param>
		/// <exception cref="ArgumentNullException">Thrown if either argument is
		/// null.</exception>
		public ArpEntry(IpAddress ipAddress, MacAddress macAddress) {
			ipAddress.ThrowIfNull("ipAddress");
			macAddress.ThrowIfNull("macAddress");
			IpAddress = ipAddress;
			MacAddress = macAddress;
			
			ExpiryTime = Simulation.Time + maxAge;
		}
コード例 #2
0
        public InterfaceOperation(Mapping.InterfaceOperation operation, Interface iface, IpAddress ipAddress = null)
            : base(operation)
        {
            this.InterfaceId = operation.InterfaceId;
            this.Interface = iface;

            this.IpAddressId = operation.IpAddressId;
            this.IpAddress = ipAddress;
        }
コード例 #3
0
ファイル: Arp.cs プロジェクト: smiley22/Network.Sim
		/// <summary>
		/// Looks up the Layer-2 (MAC-48) physical address in the ARP cache for
		/// the specified IPv4 address.
		/// </summary>
		/// <param name="ifc">The interface to look an address up for.</param>
		/// <param name="ipAddress">The IPv4 address to look up the respective
		/// MAC-48 address for.</param>
		/// <returns>A MAC-48 address or null if the lookup could not be satisfied
		/// from the ARP cache.</returns>
		/// <exception cref="ArgumentNullException">Thrown if the ipAddress parameter
		/// is null.</exception>
		public MacAddress Lookup(Interface ifc, IpAddress ipAddress) {
			ipAddress.ThrowIfNull("ipAddress");
			if (!cache.ContainsKey(ifc.Name))
				cache.Add(ifc.Name, new ArpCache());
			ArpEntry entry = cache[ifc.Name][ipAddress];
			if (entry != null && entry.Expired == false)
				return entry.MacAddress;
			return null;
		}
コード例 #4
0
ファイル: ArpPacket.cs プロジェクト: smiley22/Network.Sim
		/// <summary>
		/// Initializes a new instance of the ArpPacket class creating an ARP
		/// request message.
		/// </summary>
		/// <param name="macAddressSender">The MAC-48 address of the sender.</param>
		/// <param name="ipAddressSender">The IPv4 address of the sender.</param>
		/// <param name="ipAddressTarget">The IPv4 address of the target.</param>
		/// <exception cref="ArgumentNullException">Thrown if any of the arguments
		/// is null.</exception>
		public ArpPacket(MacAddress macAddressSender, IpAddress ipAddressSender,
			IpAddress ipAddressTarget) {
				macAddressSender.ThrowIfNull("macAddressSender");
				ipAddressSender.ThrowIfNull("ipAddressSender");
				ipAddressTarget.ThrowIfNull("ipAddressTarget");
				IsRequest = true;
				MacAddressSender = macAddressSender;
				IpAddressSender = ipAddressSender;
				IpAddressTarget = ipAddressTarget;
				// Broadcast to all stations.
				MacAddressTarget = broadcastAddress;
		}
コード例 #5
0
ファイル: Arp.cs プロジェクト: smiley22/Network.Sim
        /// <summary>
        /// Resolves the specified IPv4 address to a Layer-2 (MAC-48)
        /// physical address.
        /// </summary>
        /// <param name="ifc">The interface to look an address up for.</param>
        /// <param name="ipAddress">The IPv4 address to resolve.</param>
        /// <exception cref="ArgumentNullException">Thrown if either of the
        /// arguments is null.</exception>
        /// <remarks>This API is exposed to the next higher-up layer. In other
        /// words, it is called by the Network layer to resolve an IPv4 address
        /// to the corresponding MAC-48 address.</remarks>
        public void Resolve(Interface ifc, IpAddress ipAddress) {
			ifc.ThrowIfNull("ifc");
			ipAddress.ThrowIfNull("ipAddress");
			// If there's already a pending ARP request for the IP, don't
			// issue another one.
			if (arpInProgress.Contains(ipAddress))
				return;
			// Output an ARP request to physical broadcast address
			// FF:FF:FF:FF:FF:FF.
			arpInProgress.Add(ipAddress);
			ArpPacket packet = new ArpPacket(ifc.Nic.MacAddress, ifc.IpAddress,
				ipAddress);
			WriteLine(ifc.FullName + " is constructing an ARP request for " +
				ipAddress + ".");
			output(ifc, broadcastAddress, packet);
		}
コード例 #6
0
 static DataTypeDescriptor()
 {
     DnsName = new DnsNameDataType();
     IpAddress = new IpAddress();
     Bag = new Bag();
     Time = new Time();
     String = new StringDataType();
     Rfc822Name = new Rfc822Name();
     X500Name = new X500Name();
     Double = new DoubleDataType();
     YearMonthDuration = new YearMonthDuration();
     DaytimeDuration = new DaytimeDuration();
     DateTime = new DateTime();
     Date = new DateDataType();
     Integer = new IntegerDataType();
     Boolean = new BooleanDataType();
     HexBinary = new HexBinary();
     Base64Binary = new Base64Binary();
     AnyUri = new AnyUri();
     Function = new FunctionDataType();
 }
コード例 #7
0
        internal override void WriteXml(XmlTextWriter xmlWriter)
        {
            xmlWriter.WriteStartElement("billing_info"); // Start: billing_info

            //if a recurly js token is supplied we don't want to send billing info here
            if (string.IsNullOrEmpty(TokenId))
            {
                xmlWriter.WriteStringIfValid("first_name", FirstName);
                xmlWriter.WriteStringIfValid("last_name", LastName);
                xmlWriter.WriteStringIfValid("name_on_account", NameOnAccount);
                xmlWriter.WriteStringIfValid("address1", Address1);
                xmlWriter.WriteStringIfValid("address2", Address2);
                xmlWriter.WriteStringIfValid("city", City);
                xmlWriter.WriteStringIfValid("state", State);
                xmlWriter.WriteStringIfValid("zip", PostalCode);
                xmlWriter.WriteStringIfValid("country", Country);
                xmlWriter.WriteStringIfValid("phone", PhoneNumber);
                xmlWriter.WriteStringIfValid("vat_number", VatNumber);
                xmlWriter.WriteStringIfValid("currency", Currency);

                if (!IpAddress.IsNullOrEmpty())
                {
                    xmlWriter.WriteElementString("ip_address", IpAddress);
                }
                else
                {
                    Debug.WriteLine("Recurly Client Library: Recording IP Address is strongly recommended.");
                }

                if (!CreditCardNumber.IsNullOrEmpty())
                {
                    xmlWriter.WriteElementString("number", CreditCardNumber);
                    xmlWriter.WriteElementString("month", ExpirationMonth.AsString());
                    xmlWriter.WriteElementString("year", ExpirationYear.AsString());

                    xmlWriter.WriteStringIfValid("verification_value", VerificationValue);
                }

                if (!AccountNumber.IsNullOrEmpty())
                {
                    xmlWriter.WriteElementString("routing_number", RoutingNumber);
                    xmlWriter.WriteElementString("account_number", AccountNumber);
                    xmlWriter.WriteElementString("account_type", AccountType.ToString().EnumNameToTransportCase());
                }

                if (!PaypalBillingAgreementId.IsNullOrEmpty())
                {
                    xmlWriter.WriteElementString("paypal_billing_agreement_id", PaypalBillingAgreementId);
                }

                if (!AmazonBillingAgreementId.IsNullOrEmpty())
                {
                    xmlWriter.WriteElementString("amazon_billing_agreement_id", AmazonBillingAgreementId);
                }

                if (ExternalHppType.HasValue)
                {
                    xmlWriter.WriteElementString("external_hpp_type", ExternalHppType.Value.ToString().EnumNameToTransportCase());
                }
            }

            xmlWriter.WriteStringIfValid("token_id", TokenId);

            xmlWriter.WriteEndElement(); // End: billing_info
        }
コード例 #8
0
 public override int GetHashCode()
 {
     return(IpAddress.GetHashCode() + TcpPort.GetHashCode());
 }
コード例 #9
0
        internal override void WriteXml(XmlTextWriter xmlWriter)
        {
            xmlWriter.WriteStartElement("billing_info"); // Start: billing_info

            //if a recurly js token is supplied we don't want to send billing info here
            if (string.IsNullOrEmpty(TokenId))
            {
                xmlWriter.WriteStringIfValid("first_name", FirstName);
                xmlWriter.WriteStringIfValid("last_name", LastName);
                xmlWriter.WriteStringIfValid("company", Company);
                xmlWriter.WriteStringIfValid("name_on_account", NameOnAccount);
                xmlWriter.WriteStringIfValid("address1", Address1);
                xmlWriter.WriteStringIfValid("address2", Address2);
                xmlWriter.WriteStringIfValid("city", City);
                xmlWriter.WriteStringIfValid("state", State);
                xmlWriter.WriteStringIfValid("zip", PostalCode);
                xmlWriter.WriteStringIfValid("country", Country);
                xmlWriter.WriteStringIfValid("phone", PhoneNumber);
                xmlWriter.WriteStringIfValid("vat_number", VatNumber);
                xmlWriter.WriteStringIfValid("currency", Currency);

                if (!IpAddress.IsNullOrEmpty())
                {
                    xmlWriter.WriteElementString("ip_address", IpAddress);
                }
                else
                {
                    Debug.WriteLine("Recurly Client Library: Recording IP Address is strongly recommended.");
                }

                if (!CreditCardNumber.IsNullOrEmpty())
                {
                    xmlWriter.WriteElementString("number", CreditCardNumber);
                    xmlWriter.WriteElementString("month", ExpirationMonth.AsString());
                    xmlWriter.WriteElementString("year", ExpirationYear.AsString());

                    xmlWriter.WriteStringIfValid("verification_value", VerificationValue);
                }

                if (!AccountNumber.IsNullOrEmpty())
                {
                    xmlWriter.WriteElementString("routing_number", RoutingNumber);
                    xmlWriter.WriteElementString("account_number", AccountNumber);
                    xmlWriter.WriteElementString("account_type", AccountType.ToString().EnumNameToTransportCase());
                }

                if (!PaypalBillingAgreementId.IsNullOrEmpty())
                {
                    xmlWriter.WriteElementString("paypal_billing_agreement_id", PaypalBillingAgreementId);
                }

                if (!AmazonBillingAgreementId.IsNullOrEmpty())
                {
                    xmlWriter.WriteElementString("amazon_billing_agreement_id", AmazonBillingAgreementId);
                }

                if (!AmazonRegion.IsNullOrEmpty())
                {
                    xmlWriter.WriteElementString("amazon_region", AmazonRegion);
                }

                if (ExternalHppType.HasValue)
                {
                    xmlWriter.WriteElementString("external_hpp_type", ExternalHppType.Value.ToString().EnumNameToTransportCase());
                }

                if (!GatewayCode.IsNullOrEmpty())
                {
                    xmlWriter.WriteElementString("gateway_code", GatewayCode);
                    xmlWriter.WriteElementString("gateway_token", GatewayToken);

                    // EnumNameToTransportCase() turns MasterCard into "master_card",
                    // but it needs to be "master" for the server to accept it.
                    // Check for this edge case before writing the card_type tag.
                    var card = CardType.ToString().EnumNameToTransportCase();
                    if (card == "master_card")
                    {
                        card = "master";
                    }

                    xmlWriter.WriteElementString("card_type", card);
                }
            }

            xmlWriter.WriteStringIfValid("token_id", TokenId);

            xmlWriter.WriteEndElement(); // End: billing_info
        }
コード例 #10
0
 /// <inheritdoc />
 public ITracerouteResult Traceroute(IpAddress remoteIp, uint count, TimeSpan timeout, int maxHops)
 {
     return(new MikrotikApiTracerouteOperation(this.Address, this.TikConnection, remoteIp, count, timeout, maxHops).Execute());
 }
コード例 #11
0
ファイル: RoutingTable.cs プロジェクト: Clodo76/airvpn-client
 public void RouteRemove(IpAddress address)
 {
     RouteRemove(address, new IpAddress("255.255.255.255"));
 }
コード例 #12
0
ファイル: ArpPacket.cs プロジェクト: smiley22/Network.Sim
		/// <summary>
		/// Initializes a new instance of the ArpPacket class creating an ARP
		/// response message.
		/// </summary>
		/// <param name="macAddressSender">The MAC-48 address of the sender.</param>
		/// <param name="ipAddressSender">The IPv4 address of the sender.</param>
		/// <param name="macAddressTarget">The MAC-48 address of the target.</param>
		/// <param name="ipAddressTarget">The IPv4 address of the target.</param>
		/// <exception cref="ArgumentNullException">Thrown if any of the arguments
		/// is null.</exception>
		public ArpPacket(MacAddress macAddressSender, IpAddress ipAddressSender,
			MacAddress macAddressTarget, IpAddress ipAddressTarget)
			: this(macAddressSender, ipAddressSender, ipAddressTarget) {
				macAddressTarget.ThrowIfNull("macAddressTarget");
				MacAddressTarget = macAddressTarget;
				IsRequest = false;
		}
コード例 #13
0
        /// <summary>
        ///     The process record.
        /// </summary>
        protected override void ProcessRecord()
        {
            base.ProcessRecord();
            try
            {
                string        targetid = string.Empty;
                VipTargetType targetType;
                string        targetName = string.Empty;
                if (ParameterSetName.Equals("ServerFarm"))
                {
                    targetid   = ServerFarm.id;
                    targetType = VipTargetType.SERVER_FARM;
                    targetName = ServerFarm.name;
                }
                else
                {
                    targetid   = PersistenceProfile.id;
                    targetType = VipTargetType.PERSISTENCE_PROFILE;
                    targetName = PersistenceProfile.name;
                }

                string ipAddress = IpAddress != null?IpAddress.ToString() : string.Empty;


                Status status =
                    Connection.ApiClient.NetworkingLegacy.NetworkVip.CreateVip(Network.id, Name, Port, Protocol, targetType, targetid,
                                                                               ReplyToIcmp, InService,
                                                                               ipAddress).Result;
                if (status != null && PassThru.IsPresent)
                {
                    // Regex to extract the Id from the status result detail: Real-Server (id:b1a3aea6-37) created
                    var   regexObj = new Regex(@"\x28id\x3A([-\w]*)\x29");
                    Match match    = regexObj.Match(status.resultDetail);
                    if (match.Success && match.Groups.Count > 1)
                    {
                        var vip = new Vip
                        {
                            id            = match.Groups[1].Value,
                            name          = Name,
                            port          = Port,
                            protocol      = Protocol,
                            vipTargetId   = targetid,
                            vipTargetType = targetType,
                            ipAddress     = ipAddress,
                            replyToIcmp   = ReplyToIcmp,
                            vipTargetName = targetName,
                            inService     = InService,
                        };
                        WriteObject(vip);
                    }
                    else
                    {
                        WriteError(new ErrorRecord(new CloudComputePsException("object Id not returned from API"), "-1",
                                                   ErrorCategory.InvalidData, status));
                    }
                }

                WriteDebug(
                    string.Format(
                        "{0} resulted in {1} ({2}): {3}",
                        status.operation,
                        status.result,
                        status.resultCode,
                        status.resultDetail));
            }
            catch (AggregateException ae)
            {
                ae.Handle(
                    e =>
                {
                    if (e is ComputeApiException)
                    {
                        WriteError(new ErrorRecord(e, "-2", ErrorCategory.InvalidOperation, Connection));
                    }
                    else
                    {
// if (e is HttpRequestException)
                        ThrowTerminatingError(new ErrorRecord(e, "-1", ErrorCategory.ConnectionError, Connection));
                    }

                    return(true);
                });
            }
        }
コード例 #14
0
ファイル: RoutingTable.cs プロジェクト: Clodo76/airvpn-client
        public override void DeallowIP(IpAddress ip)
        {
            base.DeallowIP(ip);

            RouteRemove(ip);
        }
コード例 #15
0
 /// <inheritdoc />
 public abstract ITracerouteResult Traceroute(IpAddress remoteIp, uint count, TimeSpan timeout, int maxHops);
コード例 #16
0
        private void cbbSelectEquip_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            Equipment equip     = (sender as ComboBox).SelectedItem as Equipment;
            string    equipName = equip.Name;
            int       equipID   = equip.Index;
            IpAddress agentIP   = null;

            try
            {
                object strIP = App.DBHelper.returnScalar(string.Format("SELECT IP_Address FROM IPAddress WHERE(IP_EquipID = {0}) AND (IP_IsDefaultIP = 1)", equipID));
                if (strIP == null)
                {
                    MessageBox.Show("数据库中没有" + equipName + "的默认管理IP地址");
                    return;
                }
                if (IpAddress.IsIP(strIP.ToString()))
                {
                    agentIP = new IpAddress(strIP.ToString());
                }
                else
                {
                    MessageBox.Show("地址格式错误");
                    return;
                }
            }
            catch
            {
                MessageBox.Show("读取数据库出现错误\n" + e.ToString());
            }

            OctetString     community = new OctetString("public");
            AgentParameters param     = new AgentParameters(community);

            // Set SNMP version to 2 (GET-BULK only works with SNMP ver 2 and 3)
            param.Version = SnmpVersion.Ver2;
            // Construct target
            UdpTarget target = new UdpTarget((IPAddress)agentIP, 161, 2000, 1);

            // Define Oid that is the root of the MIB
            //  tree you wish to retrieve
            Oid rootOid1 = new Oid("1.3.6.1.2.1.2.2.1.1"); // ifIndex
            Oid rootOid2 = new Oid("1.3.6.1.2.1.2.2.1.2"); // ifDescr

            // This Oid represents last Oid returned by
            //  the SNMP agent
            Oid lastOid1 = (Oid)rootOid1.Clone();
            Oid lastOid2 = (Oid)rootOid2.Clone();

            // Pdu class used for all requests
            Pdu pdu = new Pdu(PduType.GetBulk);

            // In this example, set NonRepeaters value to 0
            pdu.NonRepeaters = 0;
            // MaxRepetitions tells the agent how many Oid/Value pairs to return
            // in the response.
            pdu.MaxRepetitions = 5;

            // Loop through results
            while (lastOid1 != null && lastOid2 != null)
            {
                // When Pdu class is first constructed, RequestId is set to 0
                // and during encoding id will be set to the random value
                // for subsequent requests, id will be set to a value that
                // needs to be incremented to have unique request ids for each
                // packet
                if (pdu.RequestId != 0)
                {
                    pdu.RequestId += 1;
                }
                // Clear Oids from the Pdu class.
                pdu.VbList.Clear();
                // Initialize request PDU with the last retrieved Oid
                pdu.VbList.Add(lastOid1);
                pdu.VbList.Add(lastOid2);
                // Make SNMP request
                SnmpV2Packet result = (SnmpV2Packet)target.Request(pdu, param);
                // You should catch exceptions in the Request if using in real application.

                // If result is null then agent didn't reply or we couldn't parse the reply.
                if (result != null)
                {
                    // ErrorStatus other then 0 is an error returned by
                    // the Agent - see SnmpConstants for error definitions
                    if (result.Pdu.ErrorStatus != 0)
                    {
                        // agent reported an error with the request
                        Console.WriteLine("Error in SNMP reply. Error {0} index {1}",
                                          result.Pdu.ErrorStatus,
                                          result.Pdu.ErrorIndex);
                        MessageBox.Show(string.Format("SNMP应答数据包中有错误。 Error {0} index {1}", result.Pdu.ErrorStatus, result.Pdu.ErrorIndex));
                        lastOid1 = null;
                        lastOid2 = null;
                        break;
                    }
                    else
                    {
                        // Walk through returned variable bindings
                        foreach (Vb v in result.Pdu.VbList)
                        {
                            // Check that retrieved Oid is "child" of the root OID
                            if (rootOid1.IsRootOf(v.Oid))
                            {
                                if (v.Value.Type == SnmpConstants.SMI_ENDOFMIBVIEW)
                                {
                                    lastOid1 = null;
                                }
                                else
                                {
                                    lastOid1 = v.Oid;
                                }
                                var f = v.Value;
                                //Interface interface = new Interface(v.Value.,)
                            }
                            else if (rootOid2.IsRootOf(v.Oid))
                            {
                                if (v.Value.Type == SnmpConstants.SMI_ENDOFMIBVIEW)
                                {
                                    lastOid2 = null;
                                }
                                else
                                {
                                    lastOid2 = v.Oid;
                                }
                                var f = v.Value;
                            }
                            else
                            {
                                // we have reached the end of the requested
                                // MIB tree. Set lastOid to null and exit loop
                                lastOid1 = null;
                                lastOid2 = null;
                            }



//                             if (rootOid.IsRootOf(v.Oid))
//                             {
//                                 Console.WriteLine("{0} ({1}): {2}",
//                                     v.Oid.ToString(),
//                                     SnmpConstants.GetTypeName(v.Value.Type),
//                                     v.Value.ToString());
//                                 if (v.Value.Type == SnmpConstants.SMI_ENDOFMIBVIEW)
//                                     lastOid = null;
//                                 else
//                                     lastOid = v.Oid;
//                             }
//                             else
//                             {
//                                 // we have reached the end of the requested
//                                 // MIB tree. Set lastOid to null and exit loop
//                                 lastOid = null;
//                           }
                        }
                    }
                }
                else
                {
                    Console.WriteLine("No response received from SNMP agent.");
                }
            }
            target.Close();
        }
コード例 #17
0
        private void worker_DoWork(object sender, DoWorkEventArgs e)
        {
            try {
                var component       = (DataAccess.Entity.Component)e.Argument;
                var communityString = "public";

                if (component.Options.Keys.Contains("CommunityString"))
                {
                    communityString = component.Options["CommunityString"];
                }
                if (!component.Options.Keys.Contains("OID"))
                {
                    return;
                }
                var OIDString = component.Options["OID"];

                //Process the snmp query
                // SNMP community name
                OctetString community = new OctetString(communityString);

                // Define agent parameters class
                AgentParameters param = new AgentParameters(community);
                // Set SNMP version to 1 (or 2)
                param.Version = SnmpVersion.Ver2;
                // Construct the agent address object
                // IpAddress class is easy to use here because
                //  it will try to resolve constructor parameter if it doesn't
                //  parse to an IP address
                IpAddress agent = new IpAddress(component.Device.IPAddress);

                // Construct target
                UdpTarget target = new UdpTarget((IPAddress)agent, 161, 2000, 1);

                // Pdu class used for all requests
                Pdu pdu = new Pdu(PduType.Get);
                pdu.VbList.Add(OIDString); //sysDescr


                // Make SNMP request
                SnmpV2Packet result = (SnmpV2Packet)target.Request(pdu, param);

                // If result is null then agent didn't reply or we couldn't parse the reply.
                if (result != null)
                {
                    // ErrorStatus other then 0 is an error returned by
                    // the Agent - see SnmpConstants for error definitions
                    if (result.Pdu.ErrorStatus == 0)
                    {
                        // Reply variables are returned in the same order as they were added
                        //  to the VbList
                        //Console.WriteLine("sysDescr({0}) ({1}): {2}",
                        //    result.Pdu.VbList[0].Oid.ToString(),
                        //    SnmpConstants.GetTypeName(result.Pdu.VbList[0].Value.Type),
                        //    result.Pdu.VbList[0].Value.ToString());

                        var    temp = result.Pdu.VbList[0].Value.ToString();
                        Double val;
                        if (Double.TryParse(temp, out val))
                        {
                            component.SetNewValue(val);
                            component.LastContact = DateTime.Now;
                            CompressionManager.Instance.CompressStandard(component);
                        }
                        else
                        {
                            component.SetNewValue(temp);
                            component.LastContact = DateTime.Now;
                        }

                        DataAccess.DatabaseFacade.DatabaseManager.Components.Save(component);
                    }
                }
                target.Close();

                e.Result = component;
            } catch (Exception ex) {
                var logFile = new System.IO.StreamWriter(AppDomain.CurrentDomain.BaseDirectory + "error.log", true);
                logFile.WriteLine(ex.ToString());
                logFile.Close();
            }
        }
コード例 #18
0
        public void query(string ipAdd, string comm)
        {
            // snmp community name
            OctetString community = new OctetString(comm);

            // define agent parameters class
            AgentParameters param = new AgentParameters(community);

            // Set SNMP version to 1 or 2
            param.Version = SnmpVersion.Ver1;

            // Construct the agent address object
            // IP Address is easy to use here because it will try to resolve contructor
            // parameter if it doesn't parse to an IP Address
            IPAddress ipAddress = IPAddress.Parse(ipAdd);
            IpAddress agent     = new IpAddress(ipAdd);

            // construct target
            UdpTarget target = new UdpTarget((IPAddress)agent, 161, 2000, 1);

            // pdu class use for all requests
            Pdu pdu = new Pdu(PduType.Get);

            pdu.VbList.Add("1.3.6.1.2.1.1.1.0"); //sysDescr
            pdu.VbList.Add("1.3.6.1.2.1.1.2.0"); //sysObjectID
            pdu.VbList.Add("1.3.6.1.2.1.1.3.0"); //sysUpTime
            pdu.VbList.Add("1.3.6.1.2.1.1.4.0"); //sysContact
            pdu.VbList.Add("1.3.6.1.2.1.1.5.0"); //sysName

            // Make snmp request
            SnmpV1Packet result = (SnmpV1Packet)target.Request(pdu, param);

            // If result is null then agent didn't reply or we couldn't par se the reply.
            if (result != null)
            {
                // ErrorStatus other then 0 is an error returned by
                // the Agent - see SnmpConstants for error definitions
                if (result.Pdu.ErrorStatus != 0)
                {
                    // agent reported an error with the request
                    string errStatus = Convert.ToString(result.Pdu.ErrorStatus);
                    string errIndex  = Convert.ToString(result.Pdu.ErrorIndex);
                    MessageBox.Show(errStatus, errIndex, MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                else
                {
                    for (int i = 0; i < 5; i++)
                    {
                        string sysOid  = result.Pdu.VbList[i].Oid.ToString();
                        string sysName = SnmpConstants.GetTypeName(result.Pdu.VbList[i].Value.Type);
                        string value   = result.Pdu.VbList[i].Value.ToString();

                        string[]     row  = { sysOid, sysName, value };
                        ListViewItem item = new ListViewItem(row);
                        listViewResult.Items.Add(item);
                    }
                }
            }
            else
            {
                MessageBox.Show("No response received from SNMP agent.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
コード例 #19
0
ファイル: SharpWalk.cs プロジェクト: odnanref/snrviewer
        static void remoteCall(string[] args)
        {
            // SNMP community name
            OctetString community = new OctetString("public");

            // Define agent parameters class
            AgentParameters param = new AgentParameters(community);
            // Set SNMP version to 2 (GET-BULK only works with SNMP ver 2 and 3)
            param.Version = SnmpVersion.Ver2;
            // Construct the agent address object
            // IpAddress class is easy to use here because
            //  it will try to resolve constructor parameter if it doesn't
            //  parse to an IP address
            IpAddress agent = new IpAddress("127.0.0.1");

            // Construct target
            UdpTarget target = new UdpTarget((IPAddress)agent, 161, 2000, 1);

            // Define Oid that is the root of the MIB
            //  tree you wish to retrieve
            Oid rootOid = new Oid("1.3.6.1.2.1.2.2.1.2"); // ifDescr

            // This Oid represents last Oid returned by
            //  the SNMP agent
            Oid lastOid = (Oid)rootOid.Clone();

            // Pdu class used for all requests
            Pdu pdu = new Pdu(PduType.GetBulk);

            // In this example, set NonRepeaters value to 0
            pdu.NonRepeaters = 0;
            // MaxRepetitions tells the agent how many Oid/Value pairs to return
            // in the response.
            pdu.MaxRepetitions = 5;

            // Loop through results
            while (lastOid != null)
            {
                // When Pdu class is first constructed, RequestId is set to 0
                // and during encoding id will be set to the random value
                // for subsequent requests, id will be set to a value that
                // needs to be incremented to have unique request ids for each
                // packet
                if (pdu.RequestId != 0)
                {
                    pdu.RequestId += 1;
                }
                // Clear Oids from the Pdu class.
                pdu.VbList.Clear();
                // Initialize request PDU with the last retrieved Oid
                pdu.VbList.Add(lastOid);
                // Make SNMP request
                SnmpV2Packet result = (SnmpV2Packet)target.Request(pdu, param);
                // You should catch exceptions in the Request if using in real application.

                // If result is null then agent didn't reply or we couldn't parse the reply.
                if (result != null)
                {
                    // ErrorStatus other then 0 is an error returned by
                    // the Agent - see SnmpConstants for error definitions
                    if (result.Pdu.ErrorStatus != 0)
                    {
                        // agent reported an error with the request
                        Console.WriteLine("Error in SNMP reply. Error {0} index {1}",
                            result.Pdu.ErrorStatus,
                            result.Pdu.ErrorIndex);
                        lastOid = null;
                        break;
                    }
                    else
                    {
                        // Walk through returned variable bindings
                        foreach (Vb v in result.Pdu.VbList)
                        {
                            // Check that retrieved Oid is "child" of the root OID
                            if (rootOid.IsRootOf(v.Oid))
                            {
                                Console.WriteLine("{0} ({1}): {2}",
                                    v.Oid.ToString(),
                                    SnmpConstants.GetTypeName(v.Value.Type),
                                    v.Value.ToString());
                                if (v.Value.Type == SnmpConstants.SMI_ENDOFMIBVIEW)
                                    lastOid = null;
                                else
                                    lastOid = v.Oid;
                            }
                            else
                            {
                                // we have reached the end of the requested
                                // MIB tree. Set lastOid to null and exit loop
                                lastOid = null;
                            }
                        }
                    }
                }
                else
                {
                    Console.WriteLine("No response received from SNMP agent.");
                }
            }
            target.Close();
        }
コード例 #20
0
        /// <summary>
        /// Takes a CIDR notation string and converts it to a subnet mask string 
        /// </summary>
        /// <param name="CidrString"></param>
        /// <returns></returns>
        public string ParseCidr(string CidrString)
        {
            int CidrValue = 0;
            // Trim and parse input
            bool isValidNumber = int.TryParse(CidrString.Trim('/'), out CidrValue);

            int BitCount;
            int FullOctetCount = 0;

            if (isValidNumber)
            {
                // if it is >/7 then we only need the bit count
                if (CidrValue < 8)
                {
                    BitCount = CidrValue;
                }
                else
                {
                    // Gets the ammount of populated octets and the ammount of bits in the next octet
                    FullOctetCount = CidrValue / 8;
                    BitCount = CidrValue % 8;
                }

                byte [] AddressArray = new byte[4];

                int ZeroCount = 8 - BitCount;

                // Declared on the outside because I need to know what octet it ended on
                int OctetIterator = 0;
                for (OctetIterator = 0; OctetIterator < FullOctetCount; OctetIterator++)
                {
                    AddressArray[OctetIterator] = 255;
                }

                // Build the binary for the last octet if the bit count is > 0
                // There has got to be a better way to build a binary string
                if (BitCount > 0)
                {
                    string BinaryString = "";
                    for (int i = 0; i < BitCount; i++)
                    {
                        BinaryString += "1";
                    }

                    for (int i = 0; i < ZeroCount; i++)
                    {
                        BinaryString += "0";

                    }

                    AddressArray[OctetIterator] = (byte)Convert.ToInt32(BinaryString, 2);
                }

                IpAddress ReturnAddress = new IpAddress(AddressArray);
                return ReturnAddress.ToString();

            }
            else
            {
                return "Invalid CIDR notation";
            }
        }
コード例 #21
0
 public override string ToString()
 {
     return((this.Name ?? "") + ", Ip: " + IpAddress.ToString());
 }
コード例 #22
0
ファイル: RoutingTable.cs プロジェクト: Clodo76/airvpn-client
        public override void AllowIP(IpAddress ip)
        {
            base.AllowIP(ip);

            RouteAdd(ip);
        }
コード例 #23
0
 /// <inheritdoc />
 public override ITracerouteResult Traceroute(IpAddress remoteIp, uint count, TimeSpan timeout, int maxHops)
 {
     throw new System.NotSupportedException("Traceroute is currently not supported for Ubiquiti AirOs < 5.6 devices");
 }
コード例 #24
0
ファイル: RoutingTable.cs プロジェクト: Clodo76/airvpn-client
 public void RouteAdd(IpAddress address)
 {
     RouteAdd(address, new IpAddress("255.255.255.255"), DefaultGateway, DefaultInterface);
 }
コード例 #25
0
        public override void OnJsonRouteList(Json jRoutesList)
        {
            base.OnJsonRouteList(jRoutesList);

            string netstatPath = LocateExecutable("netstat");

            if (netstatPath != "")
            {
                string result = SystemShell.Shell1(netstatPath, "-rnl");

                string[] lines = result.Split('\n');
                foreach (string line in lines)
                {
                    if (line == "Routing tables")
                    {
                        continue;
                    }
                    if (line == "Internet:")
                    {
                        continue;
                    }
                    if (line == "Internet6:")
                    {
                        continue;
                    }

                    string[] fields = UtilsString.StringCleanSpace(line).Split(' ');

                    if ((fields.Length > 0) && (fields[0].ToLowerInvariant().Trim() == "destination"))
                    {
                        continue;
                    }

                    if (fields.Length >= 7)
                    {
                        Json      jRoute  = new Json();
                        IpAddress address = new IpAddress();
                        if (fields[0].ToLowerInvariant().Trim() == "default")
                        {
                            IpAddress gateway = new IpAddress(fields[1]);
                            if (gateway.Valid == false)
                            {
                                continue;
                            }
                            if (gateway.IsV4)
                            {
                                address = IpAddress.DefaultIPv4;
                            }
                            else if (gateway.IsV6)
                            {
                                address = IpAddress.DefaultIPv6;
                            }
                        }
                        else
                        {
                            address.Parse(fields[0]);
                        }
                        if (address.Valid == false)
                        {
                            continue;
                        }
                        jRoute["address"].Value   = address.ToCIDR();
                        jRoute["gateway"].Value   = fields[1];
                        jRoute["flags"].Value     = fields[2];
                        jRoute["refs"].Value      = fields[3];
                        jRoute["use"].Value       = fields[4];
                        jRoute["mtu"].Value       = fields[5];
                        jRoute["interface"].Value = fields[6];
                        if (fields.Length > 7)
                        {
                            jRoute["expire"].Value = fields[7];
                        }
                        jRoutesList.Append(jRoute);
                    }
                }
            }
        }
コード例 #26
0
ファイル: RoutingTable.cs プロジェクト: Clodo76/airvpn-client
 public static bool IsIP(IpAddress v)
 {
     return IsIP(v.Value);
 }
コード例 #27
0
ファイル: DbAccess.cs プロジェクト: EmilJL/AdminFinal
        public Model GetDataAndCreateModel()
        {
            const string GetAdminsQuery            = "SELECT * from Admins";
            const string GetLunchPlansQuery        = "SELECT * from LunchPlans";
            const string GetMessagesQuery          = "SELECT * from Messages";
            const string GetMealsQuery             = "SELECT * from Meals";
            const string GetMealsVsLunchPlansQuery = "SELECT * from MealsVsLunchPlans";
            const string GetIpQuery = "SELECT * FROM DeviceIP";
            var          admins     = new ObservableCollection <Admin>();
            var          lunchPlans = new ObservableCollection <LunchPlan>();
            var          messages   = new ObservableCollection <Message>();
            var          meals      = new ObservableCollection <Meal>();
            var          mealsVsLunchPlansCollection = new ObservableCollection <MealsVsLunchPlans>();
            var          ip = new ObservableCollection <IpAddress>();

            try
            {
                using (SqlConnection conn = new SqlConnection(connectionString))
                {
                    conn.Open();
                    if (conn.State == System.Data.ConnectionState.Open)
                    {
                        using (SqlCommand cmd = conn.CreateCommand())
                        {
                            cmd.CommandText = GetAdminsQuery;
                            using (SqlDataReader reader = cmd.ExecuteReader())
                            {
                                while (reader.Read())
                                {
                                    var admin = new Admin();
                                    admin.Id           = reader.GetInt32(0);
                                    admin.Username     = reader.GetString(1);
                                    admin.PasswordSalt = (byte[])reader.GetValue(2);
                                    admin.PasswordHash = (byte[])reader.GetValue(3);
                                    admins.Add(admin);
                                }
                            }
                            cmd.CommandText = GetMessagesQuery;
                            using (SqlDataReader reader = cmd.ExecuteReader())
                            {
                                while (reader.Read())
                                {
                                    var message = new Message();
                                    message.Id      = reader.GetInt32(0);
                                    message.AdminId = reader.GetInt32(1);
                                    message.Date    = reader.GetDateTime(2);
                                    message.Text    = reader.GetString(3);
                                    message.Header  = reader.GetString(4);
                                    messages.Add(message);
                                }
                            }
                            cmd.CommandText = GetMealsQuery;
                            using (SqlDataReader reader = cmd.ExecuteReader())
                            {
                                while (reader.Read())
                                {
                                    var meal = new Meal();
                                    meal.Id          = reader.GetInt32(0);
                                    meal.Description = reader.GetString(1);
                                    meal.TimesChosen = reader.GetInt32(2);
                                    meals.Add(meal);
                                }
                            }
                            cmd.CommandText = GetLunchPlansQuery;
                            using (SqlDataReader reader = cmd.ExecuteReader())
                            {
                                while (reader.Read())
                                {
                                    var lunchPlan = new LunchPlan();
                                    lunchPlan.Id   = reader.GetInt32(0);
                                    lunchPlan.Week = reader.GetInt32(1);
                                    lunchPlans.Add(lunchPlan);
                                }
                            }
                            cmd.CommandText = GetMealsVsLunchPlansQuery;
                            using (SqlDataReader reader = cmd.ExecuteReader())
                            {
                                while (reader.Read())
                                {
                                    var mealsVsLunchPlans = new MealsVsLunchPlans();
                                    mealsVsLunchPlans.Id          = reader.GetInt32(0);
                                    mealsVsLunchPlans.LunchPlanId = reader.GetInt32(1);
                                    mealsVsLunchPlans.MealId      = reader.GetInt32(2);
                                    mealsVsLunchPlans.Weekday     = reader.GetString(3);
                                    mealsVsLunchPlansCollection.Add(mealsVsLunchPlans);
                                }
                            }
                            cmd.CommandText = GetIpQuery;
                            using (SqlDataReader reader = cmd.ExecuteReader())
                            {
                                while (reader.Read())
                                {
                                    var address = new IpAddress
                                    {
                                        Id = reader.GetInt32(0),
                                        Ip = reader.GetString(1)
                                    };
                                    ip.Add(address);
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception eSql)
            {
                Debug.WriteLine("Exception: " + eSql.Message);
            }
            Model model = new Model(admins, lunchPlans, messages, meals, mealsVsLunchPlansCollection, ip);

            return(model);
        }
コード例 #28
0
ファイル: Route.cs プロジェクト: smiley22/Network.Sim
        /// <summary>
        /// Initializes a new instance of the Route class.
        /// </summary>
        /// <param name="destination">The IP address of the destination network. This,
        /// together with the netmask describes the destination network id.</param>
        /// <param name="netmask">The netmask that, together with the destination
        /// parameter describes the destination network id.</param>
        /// <param name="gateway">The gateway through which the destination network
        /// can be reached.</param>
        /// <param name="interface">The local interface through which the gateway
        /// can be reached.</param>
        /// <param name="metric">The metric of using the route.</param>
		public Route(IpAddress destination, IpAddress netmask,
			IpAddress gateway, Interface @interface, int metric) {
				Init(destination, netmask, gateway, @interface, metric);
		}
コード例 #29
0
 /// <inheritdoc />
 public override bool IsApplicableVendorSpecific(IpAddress address, IQuerierOptions options)
 {
     // we only support SNMP
     return(false);
 }
コード例 #30
0
        private void SnmpReading()
        {
            //LoadData();
            //WriteToFile(TotalFleet + "  Control Total when launch Monitor Fleet");
            ReadSNMP();
            // WriteToFile(communitySNMP + "   This is the community read");


            string IPAddressMonitor = textBoxIP.Text.ToString();

            if (IPAddressMonitor != null)
            {
                // SNMP community name
                OctetString community = new OctetString(communitySNMP);
                // Define agent parameters class
                AgentParameters param = new AgentParameters(community);
                // Set SNMP version to 1 (or 2)
                param.Version = SnmpVersion.Ver1;
                // Construct the agent address object
                // IpAddress class is easy to use here because
                //  it will try to resolve constructor parameter if it doesn't
                //  parse to an IP address
                IpAddress agent  = new IpAddress(IPAddressMonitor);
                UdpTarget target = new UdpTarget((IPAddress)agent, 161, 2000, 1);
                Pdu       pdu    = new Pdu(PduType.Get);
                SetConnection();
                sql_con.Open();

                DataSet   DataSetType0   = new DataSet();
                DataTable DataTableType0 = new DataTable();
                sql_cmd = sql_con.CreateCommand();
                string CommandText = "Select * FROM oid WHERE id_type = 0";
                DB = new SQLiteDataAdapter(CommandText, sql_con);
                DataSetType0.Reset();
                DB.Fill(DataSetType0);
                DataTableType0 = DataSetType0.Tables[0];
                int TotalFleet = DataTableType0.Rows.Count;
                sql_con.Close();
                foreach (DataRow rowType0 in DataTableType0.Rows)
                {
                    pdu.VbList.Add(rowType0["oid"].ToString());
                }

                SnmpV1Packet result = null;
                try
                {
                    result = (SnmpV1Packet)target.Request(pdu, param) as SnmpV1Packet;
                }
                catch (Exception ex)
                {
                    WriteToFile(DateTime.Now + " - " + ex);
                }
                finally
                {
                    if (result == null)
                    {
                    }
                    // If result is null then agent didn't reply or we couldn't parse the reply.
                    if (result != null)
                    {
                        // ErrorStatus other then 0 is an error returned by
                        // the Agent - see SnmpConstants for error definitions
                        if (result.Pdu.ErrorStatus != 0)
                        {
                            // agent reported an error with the request
                            WriteToFile(DateTime.Now + "   " + IPAddressMonitor + "       " + result.Pdu.ErrorStatus + "   " + result.Pdu.ErrorIndex);
                        }
                        else
                        {
                            textBoxsysDescr.Text = result.Pdu.VbList[0].Value.ToString();

                            textBoxsysUptime.Text   = result.Pdu.VbList[1].Value.ToString();
                            textBoxsysContact.Text  = result.Pdu.VbList[2].Value.ToString();
                            textBoxsysName.Text     = result.Pdu.VbList[3].Value.ToString();
                            textBoxsysLocation.Text = result.Pdu.VbList[4].Value.ToString();


                            SetConnection();
                            sql_con.Open();

                            sql_cmd = sql_con.CreateCommand();
                            string CommandText1 = "Select * FROM library WHERE name= '" + result.Pdu.VbList[0].Value.ToString() + "'";

                            DB = new SQLiteDataAdapter(CommandText1, sql_con);
                            DataSetType0.Reset();

                            DB.Fill(DataSetType0);
                            DataTableType0 = DataSetType0.Tables[0];
                            int TotalType = 0;
                            TotalType = DataTableType0.Rows.Count;
                            sql_con.Close();
                            if (TotalType == 0)
                            {
                                MessageBox.Show("This device type does not exist in our database.");
                                TransfertType = result.Pdu.VbList[0].Value.ToString();
                                using (var newtype = new AddType(TransfertType))
                                {
                                    var result1 = newtype.ShowDialog();
                                    if (result1 == DialogResult.OK)
                                    {
                                        string val = newtype.ReturnValue1;
                                        textBoxType.Text = val;
                                    }
                                }
                            }

                            foreach (DataRow rowType0 in DataTableType0.Rows)
                            {
                                textBoxType.Text = rowType0["conversion"].ToString();
                            }
                        }
                    }

                    target.Close();
                }
            }
        }
コード例 #31
0
 /// <summary>
 /// Returns the hashcode of this Object
 /// </summary>
 /// <returns>Hash code (int)</returns>
 public override int GetHashCode()
 {
     // Credit: http://stackoverflow.com/a/263416/677735
     unchecked             // Overflow is fine, just wrap
     {
         int hash = 41;
         // Suitable nullity checks etc, of course :)
         if (Id != null)
         {
             hash = hash * 59 + Id.GetHashCode();
         }
         if (LogMessageTypeId != null)
         {
             hash = hash * 59 + LogMessageTypeId.GetHashCode();
         }
         if (ApplicationName != null)
         {
             hash = hash * 59 + ApplicationName.GetHashCode();
         }
         if (ApplicationMethod != null)
         {
             hash = hash * 59 + ApplicationMethod.GetHashCode();
         }
         if (IpAddress != null)
         {
             hash = hash * 59 + IpAddress.GetHashCode();
         }
         if (LoginToken != null)
         {
             hash = hash * 59 + LoginToken.GetHashCode();
         }
         if (ShortMessage != null)
         {
             hash = hash * 59 + ShortMessage.GetHashCode();
         }
         if (RequestHttpMethod != null)
         {
             hash = hash * 59 + RequestHttpMethod.GetHashCode();
         }
         if (RequestUri != null)
         {
             hash = hash * 59 + RequestUri.GetHashCode();
         }
         if (RequestParams != null)
         {
             hash = hash * 59 + RequestParams.GetHashCode();
         }
         if (RequestBody != null)
         {
             hash = hash * 59 + RequestBody.GetHashCode();
         }
         if (StatusCode != null)
         {
             hash = hash * 59 + StatusCode.GetHashCode();
         }
         if (ResponseContent != null)
         {
             hash = hash * 59 + ResponseContent.GetHashCode();
         }
         if (FullMessage != null)
         {
             hash = hash * 59 + FullMessage.GetHashCode();
         }
         if (Exception != null)
         {
             hash = hash * 59 + Exception.GetHashCode();
         }
         if (Trace != null)
         {
             hash = hash * 59 + Trace.GetHashCode();
         }
         if (Logged != null)
         {
             hash = hash * 59 + Logged.GetHashCode();
         }
         return(hash);
     }
 }
コード例 #32
0
        void ReadOptions()
        {
            Storage s = Engine.Instance.Storage;

            // General

            GuiUtils.SetCheck(ChkConnect, s.GetBool("connect"));
            GuiUtils.SetCheck(ChkNetLock, s.GetBool("netlock"));

            GuiUtils.SetCheck(ChkGeneralStartLast, s.GetBool("servers.startlast"));
            GuiUtils.SetCheck(ChkGeneralOsxVisible, s.GetBool("gui.osx.visible"));
            // GuiUtils.SetCheck (ChkGeneralOsxDock, s.GetBool ("gui.osx.dock")); // See this FAQ: https://airvpn.org/topic/13331-its-possible-to-hide-the-icon-in-dock-bar-under-os-x/
            GuiUtils.SetCheck(ChkGeneralOsxNotifications, s.GetBool("gui.osx.notifications"));
            GuiUtils.SetCheck(ChkUiSystemBarShowInfo, s.GetBool("gui.osx.sysbar.show_info"));
            GuiUtils.SetCheck(ChkUiSystemBarShowSpeed, s.GetBool("gui.osx.sysbar.show_speed"));
            GuiUtils.SetCheck(ChkUiSystemBarShowServer, s.GetBool("gui.osx.sysbar.show_server"));

            GuiUtils.SetCheck(ChkExitConfirm, s.GetBool("gui.exit_confirm"));

            // UI
            string uiUnit = s.Get("ui.unit");

            if (uiUnit == "bytes")
            {
                GuiUtils.SetSelected(CboUiUnit, Messages.WindowsSettingsUiUnit1);
            }
            else if (uiUnit == "bits")
            {
                GuiUtils.SetSelected(CboUiUnit, Messages.WindowsSettingsUiUnit2);
            }
            else
            {
                GuiUtils.SetSelected(CboUiUnit, Messages.WindowsSettingsUiUnit0);
            }
            GuiUtils.SetCheck(ChkUiIEC, s.GetBool("ui.iec"));

            /*
             * string interfaceMode = GuiUtils.InterfaceColorMode ();
             * if (interfaceMode == "Dark")
             *      GuiUtils.SetSelected (CboGeneralOsxInterfaceStyle,"Dark");
             * else
             *      GuiUtils.SetSelected (CboGeneralOsxInterfaceStyle,"Default");
             */

            // Protocols
            String protocol = s.Get("mode.protocol").ToUpperInvariant();
            int    port     = s.GetInt("mode.port");
            int    entryIP  = s.GetInt("mode.alt");

            if (protocol == "AUTO")
            {
                GuiUtils.SetCheck(ChkProtocolsAutomatic, true);
            }
            else
            {
                bool found = false;

                int iRow = 0;
                foreach (TableProtocolsControllerItem itemProtocol in TableProtocolsController.Items)
                {
                    if ((itemProtocol.Protocol == protocol) &&
                        (itemProtocol.Port == port) &&
                        (itemProtocol.IP == entryIP))
                    {
                        found = true;
                        TableProtocols.SelectRow(iRow, false);
                        TableProtocols.ScrollRowToVisible(iRow);
                        break;
                    }
                    iRow++;
                }

                if (found == false)
                {
                    GuiUtils.SetCheck(ChkProtocolsAutomatic, true);
                }
                else
                {
                    GuiUtils.SetCheck(ChkProtocolsAutomatic, false);
                }
            }

            // Proxy

            GuiUtils.SetSelected(CboProxyType, s.Get("proxy.mode"));
            if (s.Get("proxy.when") == "always")
            {
                GuiUtils.SetSelected(CboProxyWhen, Messages.WindowsSettingsProxyWhenAlways);
            }
            else if (s.Get("proxy.when") == "web")
            {
                GuiUtils.SetSelected(CboProxyWhen, Messages.WindowsSettingsProxyWhenWeb);
            }
            else if (s.Get("proxy.when") == "openvpn")
            {
                GuiUtils.SetSelected(CboProxyWhen, Messages.WindowsSettingsProxyWhenOpenVPN);
            }
            else if (s.Get("proxy.when") == "none")
            {
                GuiUtils.SetSelected(CboProxyWhen, Messages.WindowsSettingsProxyWhenNone);
            }
            else
            {
                GuiUtils.SetSelected(CboProxyWhen, Messages.WindowsSettingsProxyWhenAlways);
            }
            TxtProxyHost.StringValue = s.Get("proxy.host");
            TxtProxyPort.StringValue = s.Get("proxy.port");
            GuiUtils.SetSelected(CboProxyAuthentication, s.Get("proxy.auth"));
            TxtProxyLogin.StringValue              = s.Get("proxy.login");
            TxtProxyPassword.StringValue           = s.Get("proxy.password");
            TxtProxyTorControlPort.StringValue     = s.Get("proxy.tor.control.port");
            TxtProxyTorControlPassword.StringValue = s.Get("proxy.tor.control.password");

            // Routes
            GuiUtils.SetSelected(CboRoutesOtherwise, RouteDirectionToDescription(s.Get("routes.default")));

            string routes = s.Get("routes.custom");

            string[] routes2 = routes.Split(';');
            foreach (string route in routes2)
            {
                string[] routeEntries = route.Split(',');
                if (routeEntries.Length < 2)
                {
                    continue;
                }

                TableRoutingControllerItem item = new TableRoutingControllerItem();
                item.Ip     = routeEntries[0];
                item.Action = routeEntries[1];
                item.Icon   = routeEntries[1];
                if (routeEntries.Length == 3)
                {
                    item.Notes = routeEntries[2];
                }
                TableRoutingController.Items.Add(item);
            }

            TableRoutingController.RefreshUI();

            // Advanced - General

            GuiUtils.SetCheck(ChkAdvancedExpertMode, s.GetBool("advanced.expert"));
            GuiUtils.SetCheck(ChkAdvancedCheckRoute, s.GetBool("advanced.check.route"));
            string ipV6Mode = s.Get("ipv6.mode");

            if (ipV6Mode == "none")
            {
                GuiUtils.SetSelected(CboIpV6, "None");
            }
            else if (ipV6Mode == "disable")
            {
                GuiUtils.SetSelected(CboIpV6, "Disable");
            }
            else
            {
                GuiUtils.SetSelected(CboIpV6, "None");
            }

            GuiUtils.SetCheck(ChkAdvancedPingerEnabled, s.GetBool("pinger.enabled"));
            GuiUtils.SetCheck(ChkRouteRemoveDefaultGateway, s.GetBool("routes.remove_default"));

            TxtAdvancedOpenVpnPath.StringValue = s.Get("tools.openvpn.path");
            GuiUtils.SetCheck(ChkAdvancedSkipAlreadyRun, s.GetBool("advanced.skip_alreadyrun"));
            GuiUtils.SetCheck(ChkAdvancedProviders, s.GetBool("advanced.providers"));

            int manifestRefresh = s.GetInt("advanced.manifest.refresh");

            if (manifestRefresh == 60)
            {
                GuiUtils.SetSelected(CboAdvancedManifestRefresh, "Every one hour");
            }
            else if (manifestRefresh == 10)
            {
                GuiUtils.SetSelected(CboAdvancedManifestRefresh, "Every ten minute");
            }
            else if (manifestRefresh == 1)
            {
                GuiUtils.SetSelected(CboAdvancedManifestRefresh, "Every minute");
            }
            else if (manifestRefresh == 0)
            {
                GuiUtils.SetSelected(CboAdvancedManifestRefresh, "Never");
            }
            else
            {
                GuiUtils.SetSelected(CboAdvancedManifestRefresh, "Automatic");
            }

            int openVpnSndBuf = s.GetInt("openvpn.sndbuf");

            if (openVpnSndBuf == -2)
            {
                GuiUtils.SetSelected(CboOpenVpnSndBuf, Messages.Automatic);
            }
            else if (openVpnSndBuf == -1)
            {
                GuiUtils.SetSelected(CboOpenVpnSndBuf, Messages.WindowsSettingsOpenVpnDefault);
            }
            else if (openVpnSndBuf == 1024 * 8)
            {
                GuiUtils.SetSelected(CboOpenVpnSndBuf, "8 KB");
            }
            else if (openVpnSndBuf == 1024 * 16)
            {
                GuiUtils.SetSelected(CboOpenVpnSndBuf, "16 KB");
            }
            else if (openVpnSndBuf == 1024 * 32)
            {
                GuiUtils.SetSelected(CboOpenVpnSndBuf, "32 KB");
            }
            else if (openVpnSndBuf == 1024 * 64)
            {
                GuiUtils.SetSelected(CboOpenVpnSndBuf, "64 KB");
            }
            else if (openVpnSndBuf == 1024 * 128)
            {
                GuiUtils.SetSelected(CboOpenVpnSndBuf, "128 KB");
            }
            else if (openVpnSndBuf == 1024 * 256)
            {
                GuiUtils.SetSelected(CboOpenVpnSndBuf, "256 KB");
            }
            else if (openVpnSndBuf == 1024 * 512)
            {
                GuiUtils.SetSelected(CboOpenVpnSndBuf, "512 KB");
            }

            int openVpnRcvBuf = s.GetInt("openvpn.rcvbuf");

            if (openVpnRcvBuf == -2)
            {
                GuiUtils.SetSelected(CboOpenVpnRcvBuf, Messages.Automatic);
            }
            else if (openVpnRcvBuf == -1)
            {
                GuiUtils.SetSelected(CboOpenVpnRcvBuf, Messages.WindowsSettingsOpenVpnDefault);
            }
            else if (openVpnRcvBuf == 1024 * 8)
            {
                GuiUtils.SetSelected(CboOpenVpnRcvBuf, "8 KB");
            }
            else if (openVpnRcvBuf == 1024 * 16)
            {
                GuiUtils.SetSelected(CboOpenVpnRcvBuf, "16 KB");
            }
            else if (openVpnRcvBuf == 1024 * 32)
            {
                GuiUtils.SetSelected(CboOpenVpnRcvBuf, "32 KB");
            }
            else if (openVpnRcvBuf == 1024 * 64)
            {
                GuiUtils.SetSelected(CboOpenVpnRcvBuf, "64 KB");
            }
            else if (openVpnRcvBuf == 1024 * 128)
            {
                GuiUtils.SetSelected(CboOpenVpnRcvBuf, "128 KB");
            }
            else if (openVpnRcvBuf == 1024 * 256)
            {
                GuiUtils.SetSelected(CboOpenVpnRcvBuf, "256 KB");
            }
            else if (openVpnRcvBuf == 1024 * 512)
            {
                GuiUtils.SetSelected(CboOpenVpnRcvBuf, "512 KB");
            }

            // Advanced - DNS

            string dnsMode = s.Get("dns.mode");

            if (dnsMode == "none")
            {
                GuiUtils.SetSelected(CboDnsSwitchMode, "Disabled");
            }
            else
            {
                GuiUtils.SetSelected(CboDnsSwitchMode, "Automatic");
            }

            GuiUtils.SetCheck(ChkDnsCheck, s.GetBool("dns.check"));

            TableDnsServersController.Clear();
            string[] dnsServers = s.Get("dns.servers").Split(',');
            foreach (string dnsServer in dnsServers)
            {
                if (IpAddress.IsIP(dnsServer))
                {
                    TableDnsServersController.Add(dnsServer);
                }
            }

            // Advanced - Lock
            string lockMode = s.Get("netlock.mode");

            GuiUtils.SetSelected(CboLockMode, "None");
            if (lockMode == "auto")
            {
                GuiUtils.SetSelected(CboLockMode, "Automatic");
            }
            else
            {
                foreach (NetworkLockPlugin lockPlugin in Engine.Instance.NetworkLockManager.Modes)
                {
                    if (lockPlugin.GetCode() == lockMode)
                    {
                        GuiUtils.SetSelected(CboLockMode, lockPlugin.GetName());
                    }
                }
            }
            GuiUtils.SetCheck(ChkLockAllowPrivate, s.GetBool("netlock.allow_private"));
            GuiUtils.SetCheck(ChkLockAllowPing, s.GetBool("netlock.allow_ping"));
            GuiUtils.SetCheck(ChkLockAllowDNS, s.GetBool("netlock.allow_dns"));
            TxtLockAllowedIPS.StringValue = s.Get("netlock.allowed_ips");

            // Advanced - Logging
            GuiUtils.SetCheck(ChkLoggingEnabled, s.GetBool("log.file.enabled"));
            GuiUtils.SetCheck(ChkLogLevelDebug, s.GetBool("log.level.debug"));
            TxtLoggingPath.StringValue = s.Get("log.file.path");

            // Advanced - OVPN Directives
            GuiUtils.SetSelected(CboOpenVpnDirectivesSkipDefault, (s.GetBool("openvpn.skip_defaults") ? Messages.WindowsSettingsOpenVpnDirectivesDefaultSkip2 : Messages.WindowsSettingsOpenVpnDirectivesDefaultSkip1));
            TxtAdvancedOpenVpnDirectivesDefault.StringValue = s.Get("openvpn.directives");
            TxtAdvancedOpenVpnDirectivesCustom.StringValue  = s.Get("openvpn.custom");
            TxtOpenVpnDirectivesCustomPath.StringValue      = s.Get("openvpn.directives.path");

            // Advanced - Events
            ReadOptionsEvent("app.start", 0);
            ReadOptionsEvent("app.stop", 1);
            ReadOptionsEvent("session.start", 2);
            ReadOptionsEvent("session.stop", 3);
            ReadOptionsEvent("vpn.pre", 4);
            ReadOptionsEvent("vpn.up", 5);
            ReadOptionsEvent("vpn.down", 6);

            TableAdvancedEventsController.RefreshUI();
        }
コード例 #33
0
        public static XmlDocument FetchUrls(string title, string authPublicKey, List <string> urls, Dictionary <string, string> parameters)
        {
            parameters["login"]    = Engine.Instance.Storage.Get("login");
            parameters["password"] = Engine.Instance.Storage.Get("password");
            parameters["system"]   = Platform.Instance.GetSystemCode();
            parameters["version"]  = Constants.VersionInt.ToString(CultureInfo.InvariantCulture);

            string firstError = "";
            int    hostN      = 0;

            foreach (string url in urls)
            {
                string host = Utils.HostFromUrl(url);

                hostN++;
                if (IpAddress.IsIP(host) == false)
                {
                    // If locked network are enabled, skip the hostname and try only by IP.
                    // To avoid DNS issue (generally, to avoid losing time).
                    if (Engine.Instance.NetworkLockManager.IsDnsResolutionAvailable(host) == false)
                    {
                        continue;
                    }
                }

                try
                {
                    RouteScope  routeScope = new RouteScope(host);
                    XmlDocument xmlDoc     = FetchUrl(authPublicKey, url, parameters);
                    routeScope.End();
                    if (xmlDoc == null)
                    {
                        throw new Exception("No answer.");
                    }

                    if (xmlDoc.DocumentElement.Attributes["error"] != null)
                    {
                        throw new Exception(xmlDoc.DocumentElement.Attributes["error"].Value);
                    }

                    return(xmlDoc);
                }
                catch (Exception e)
                {
                    string info      = e.Message;
                    string proxyMode = Engine.Instance.Storage.Get("proxy.mode").ToLowerInvariant();
                    string proxyWhen = Engine.Instance.Storage.Get("proxy.when").ToLowerInvariant();
                    string proxyAuth = Engine.Instance.Storage.Get("proxy.auth").ToLowerInvariant();
                    if (proxyMode != "none")
                    {
                        info += " - with '" + proxyMode + "' (" + proxyWhen + ") proxy and '" + proxyAuth + "' auth";
                    }

                    if (Engine.Instance.Storage.GetBool("advanced.expert"))
                    {
                        Engine.Instance.Logs.Log(LogType.Verbose, MessagesFormatter.Format(Messages.ExchangeTryFailed, title, hostN.ToString(), info));
                    }

                    if (firstError == "")
                    {
                        firstError = info;
                    }
                }
            }

            throw new Exception(firstError);
        }
コード例 #34
0
        public void trapReceiver()
        {
            Socket     socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
            IPEndPoint ipep   = new IPEndPoint(IPAddress.Any, 162);
            EndPoint   ep     = (EndPoint)ipep;

            socket.Bind(ep);

            socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, 0);
            bool run   = true;
            int  inlen = -1;

            while (run)
            {
                byte[]     indata    = new byte[16 * 1024];
                IpAddress  addressIP = new IpAddress(address);
                IPEndPoint peer      = new IPEndPoint((IPAddress)addressIP, 0);
                EndPoint   inep      = (EndPoint)peer;
                try
                {
                    inlen = socket.ReceiveFrom(indata, ref inep);
                }
                catch (Exception ex)
                {
                    Console.WriteLine("Exception {0}", ex.Message);
                    inlen = -1;
                }
                if (inlen > 0)
                {
                    int ver = SnmpPacket.GetProtocolVersion(indata, inlen);
                    if (ver == (int)SnmpVersion.Ver1)
                    {
                        SnmpV1TrapPacket pkt  = new SnmpV1TrapPacket();
                        string           date = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                        List <VarBind>   varBindContentList = new List <VarBind>();
                        pkt.decode(indata, inlen);

                        foreach (Vb v in pkt.Pdu.VbList)
                        {
                            varBindContentList.Add(new VarBind(v.Oid.ToString(), SnmpConstants.GetTypeName(v.Value.Type), v.Value.ToString()));
                        }
                        string ruleName = "NULL";
                        varBindListPerTrap.Add(trapCounter, varBindContentList);
                        windowHandler.addTrap(getGenericType(pkt.Pdu.Generic), pkt.Pdu.AgentAddress.ToString(), date, ruleName);
                        trapCounter++;
                    }
                    else
                    {
                        SnmpV2Packet   pkt  = new SnmpV2Packet();
                        string         date = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                        List <VarBind> varBindContentList = new List <VarBind>();
                        pkt.decode(indata, inlen);

                        if ((SnmpSharpNet.PduType)pkt.Pdu.Type != PduType.V2Trap)
                        {
                        }
                        else
                        {
                            foreach (Vb v in pkt.Pdu.VbList)
                            {
                                varBindContentList.Add(new VarBind(v.Oid.ToString(), SnmpConstants.GetTypeName(v.Value.Type), v.Value.ToString()));
                            }
                            string ruleName = "NULL";
                            varBindListPerTrap.Add(trapCounter, varBindContentList);
                            windowHandler.addTrap(pkt.Pdu.TrapObjectID.ToString(), "?", date, ruleName);
                            trapCounter++;
                        }
                    }
                }
                else
                {
                    if (inlen == 0)
                    {
                        Console.WriteLine("Zero length packet received.");
                    }
                }
            }
        }
コード例 #35
0
        public override void OnBuildOvpn(ConnectionInfo connection, OvpnBuilder ovpn)
        {
            base.OnBuildOvpn(connection, ovpn);

            ConnectionMode mode = GetMode();

            int proxyPort = 0;

            if (mode.Protocol == "SSH")
            {
                proxyPort = Engine.Instance.Storage.GetInt("ssh.port");
                if (proxyPort == 0)
                {
                    proxyPort = RandomGenerator.GetInt(1024, 64 * 1024);
                }
            }
            else if (mode.Protocol == "SSL")
            {
                proxyPort = Engine.Instance.Storage.GetInt("ssl.port");
                if (proxyPort == 0)
                {
                    proxyPort = RandomGenerator.GetInt(1024, 64 * 1024);
                }
            }
            else
            {
                proxyPort = 0;
            }

            {
                string modeDirectives = mode.Directives;
                string paramUserTA    = "";
                if (User != null)
                {
                    paramUserTA = Utils.XmlGetAttributeString(User, "ta", "");
                }
                modeDirectives = modeDirectives.Replace("{@user-ta}", paramUserTA);
                ovpn.AppendDirectives(modeDirectives, "Mode level");
            }

            // Pick the IP
            IpAddress ip            = null;
            string    protocolEntry = Engine.Instance.Storage.Get("protocol.ip.entry");

            if (protocolEntry == "ipv6-ipv4")
            {
                ip = connection.IpsEntry.GetV6ByIndex(mode.EntryIndex);
                if (ip == null)
                {
                    ip = connection.IpsEntry.GetV4ByIndex(mode.EntryIndex);
                }
            }
            else if (protocolEntry == "ipv4-ipv6")
            {
                ip = connection.IpsEntry.GetV4ByIndex(mode.EntryIndex);
                if (ip == null)
                {
                    ip = connection.IpsEntry.GetV6ByIndex(mode.EntryIndex);
                }
            }
            else if (protocolEntry == "ipv6-only")
            {
                ip = connection.IpsEntry.GetV6ByIndex(mode.EntryIndex);
            }
            else if (protocolEntry == "ipv4-only")
            {
                ip = connection.IpsEntry.GetV4ByIndex(mode.EntryIndex);
            }

            if (ip != null)
            {
                if (mode.Protocol == "SSH")
                {
                    ovpn.AppendDirective("remote", "127.0.0.1 " + Conversions.ToString(proxyPort), "");
                }
                else if (mode.Protocol == "SSL")
                {
                    ovpn.AppendDirective("remote", "127.0.0.1 " + Conversions.ToString(proxyPort), "");
                }
                else
                {
                    ovpn.AppendDirective("remote", ip.AddressQ + " " + mode.Port.ToString(), "");
                }

                string routesDefault = Engine.Instance.Storage.Get("routes.default");
                if (routesDefault == "in")
                {
                    if ((mode.Protocol == "SSH") || (mode.Protocol == "SSL"))
                    {
                        ovpn.AppendDirective("route", ip.ToOpenVPN() + " net_gateway", "VPN Entry IP");                         // ClodoIPv6 // ToFix
                    }
                }
            }

            ovpn.Protocol  = mode.Protocol; // TOCLEAN
            ovpn.Address   = ip;
            ovpn.Port      = mode.Port;
            ovpn.ProxyPort = proxyPort;
        }
コード例 #36
0
ファイル: SystemHelper.cs プロジェクト: lolly4/Version3
        private void GetExternalIpAddress(object o)
        {
            string module = $"{MethodBase.GetCurrentMethod().Name}()";

            try
            {
                string message;
                IpAddress = "0.0.0.0";

                for (int i = 0; i < 2; i++)
                {
                    foreach (string place in _placesToTry)
                    {
                        _attempts++;

                        try
                        {
                            message = $"Attempt #{_attempts} using '{place}'";
                            StartUpTimings.Add(message);
                            Debug.WriteLine(message);

                            if (place.Contains("chem4word"))
                            {
                                GetInternalVersion(place);
                            }
                            else
                            {
                                GetExternalVersion(place);
                            }

                            // Exit out of inner loop
                            if (!IpAddress.Contains("0.0.0.0"))
                            {
                                break;
                            }
                        }
                        catch (Exception exception)
                        {
                            Debug.WriteLine(exception.Message);
                            StartUpTimings.Add(exception.Message);
                        }
                    }

                    // Exit out of outer loop
                    if (!IpAddress.Contains("0.0.0.0"))
                    {
                        break;
                    }
                }

                if (IpAddress.Contains("0.0.0.0"))
                {
                    // Handle failure
                    IpAddress = "8.8.8.8";
                }

                _ipStopwatch.Stop();

                message = $"{module} took {_ipStopwatch.ElapsedMilliseconds.ToString("#,000", CultureInfo.InvariantCulture)}ms";
                StartUpTimings.Add(message);
                Debug.WriteLine(message);
            }
            catch (ThreadAbortException threadAbortException)
            {
                // Do Nothing
                Debug.WriteLine(threadAbortException.Message);
            }
            catch (Exception exception)
            {
                Debug.WriteLine(exception.Message);
                StartUpTimings.Add(exception.Message);
            }
        }
コード例 #37
0
ファイル: Class_snmpwalk.cs プロジェクト: satoyoshipc/snmpDG
        //v2の時
        private int getBulk(AgentParameters param, Form_snmpDataGet form)
        {
            try {
                int ret = 0;
                //結果格納
                resultHashL = new List <Dictionary <string, string> >();
                _headerList = new List <string>();

                tablearray = new Dictionary <string, List <string> >();



                int       flg   = 0;
                IpAddress agent = new IpAddress(INPUT.hostname);

                UdpTarget target = new UdpTarget((IPAddress)agent, 161, 5000, 1);                       // アドレス ポート 待ち時間 リトライ

                Oid rootOid = new Oid(INPUT.oid);

                Oid lastOid = (Oid)rootOid.Clone();

                // Pdu class used for all requests
                Pdu pdu = new Pdu(PduType.GetBulk);


                pdu.NonRepeaters = 0;

                pdu.MaxRepetitions = 50;

                // Loop through results
                while (lastOid != null)
                {
                    System.Windows.Forms.Application.DoEvents();

                    if (form.cancelflg)
                    {
                        //中断された時
                        form.cancelflg = false;
                        break;
                    }

                    if (pdu.RequestId != 0)
                    {
                        pdu.RequestId += 1;
                    }

                    // Clear Oids from the Pdu class.
                    pdu.VbList.Clear();

                    // Initialize request PDU with the last retrieved Oid
                    pdu.VbList.Add(lastOid);

                    // Make SNMP request
                    System.Threading.Thread.Sleep(15);
                    SnmpV2Packet result = (SnmpV2Packet)target.Request(pdu, param);

                    //Console.WriteLine("{0}  {1}  ", result.Pdu.ErrorStatus,result.Pdu.ErrorIndex);

                    // You should catch exceptions in the Request if using in real application.
                    // If result is null then agent didn't reply or we couldn't parse the reply.
                    if (result != null)
                    {
                        // ErrorStatus other then 0 is an error returned by
                        // the Agent - see SnmpConstants for error definitions
                        if (result.Pdu.ErrorStatus != 0)
                        {
                            // agent reported an error with the request
                            Errormsg = string.Format("Error in SNMP reply. Error {0} index {1}",
                                                     result.Pdu.ErrorStatus,
                                                     result.Pdu.ErrorIndex);
                            lastOid = null;
                            ret     = -1;
                            break;
                        }
                        else
                        {
                            int i = 0;
                            // Walk through returned variable bindings
                            foreach (Vb v in result.Pdu.VbList)
                            {
                                // Check that retrieved Oid is "child" of the root OID
                                if (rootOid.IsRootOf(v.Oid))
                                {
                                    //tableget
                                    //値の取得
                                    Dictionary <string, string> hashtbl = new Dictionary <string, string>();

                                    if (INPUT.method == 3)
                                    {
                                        //テーブル用データの取得
                                        getForTable(v, ref flg);
                                    }
                                    else
                                    {
                                        hashtbl["oid"]  = v.Oid.ToString();
                                        hashtbl["type"] = SnmpConstants.GetTypeName(v.Value.Type);

                                        //ifdescの時日本語の可能性あり
                                        //1.3.6.1.2.1.2.2.1.2 ifdesc
                                        //1.3.6.1.2.1.25.3.2.1.3. hrDeviceDescr
                                        if (0 <= v.Oid.ToString().IndexOf("1.3.6.1.2.1.2.2.1.2.") | 0 <= v.Oid.ToString().IndexOf("1.3.6.1.2.1.25.3.2.1.3."))
                                        {
                                            hashtbl["value"] = convertJP(v.Value.ToString());
                                        }
                                        else
                                        {
                                            if (0 <= v.Oid.ToString().IndexOf("1.3.6.1.2.1.2.2.1.3."))
                                            {
                                                hashtbl["value"] = Util.ifTypeConv(v.Value.ToString());
                                            }
                                            else if (0 <= v.Oid.ToString().IndexOf("1.3.6.1.2.1.2.2.1.7.") | 0 <= v.Oid.ToString().IndexOf("1.3.6.1.2.1.2.2.1.8."))
                                            {
                                                hashtbl["value"] = Util.convIfStatus(v.Value.ToString());
                                            }
                                            else
                                            {
                                                string value = v.Value.ToString();

                                                //TimeTick型の時はミリ秒も出力する
                                                if (hashtbl["type"] == SnmpConstants.SMI_TIMETICKS_STR)
                                                {
                                                    TimeTicks timeti = (TimeTicks)v.Value;
                                                    value = "(" + timeti.Milliseconds.ToString() + "ms)" + v.Value.ToString();
                                                }
                                                hashtbl["value"] = value;
                                            }
                                        }

                                        //リストに格納
                                        resultHashL.Add(hashtbl);
                                    }
                                    if (v.Value.Type == SnmpConstants.SMI_ENDOFMIBVIEW)
                                    {
                                        lastOid = null;
                                    }
                                    else
                                    {
                                        lastOid = v.Oid;
                                    }
                                }
                                else
                                {
                                    // we have reached the end of the requested
                                    // MIB tree. Set lastOid to null and exit loop
                                    lastOid = null;
                                }
                                i++;
                            }
                        }
                    }
                    else
                    {
                        Console.WriteLine("No response received from SNMP agent.");
                    }
                }
                target.Close();
                return(ret);
            }
            catch {
                throw;
            }
        }
コード例 #38
0
ファイル: Route.cs プロジェクト: smiley22/Network.Sim
        /// <summary>
        /// Initializes a new instance.
        /// </summary>
        /// <param name="destination">The IP address of the destination network. This,
        /// together with the netmask describes the destination network id.</param>
        /// <param name="netmask">The netmask that, together with the destination
        /// parameter describes the destination network id.</param>
        /// <param name="gateway">The gateway through which the destination network
        /// can be reached.</param>
        /// <param name="interface">The local interface through which the gateway
        /// can be reached.</param>
        /// <param name="metric">The metric of using the route.</param>
        void Init(IpAddress destination, IpAddress netmask, IpAddress gateway,
			Interface @interface, int metric) {
			destination.ThrowIfNull(nameof(destination));
			netmask.ThrowIfNull(nameof(netmask));
			@interface.ThrowIfNull(nameof(@interface));
			if (metric < 0)
				throw new ArgumentException("The metric value must be greater than " +
					"or equal to zero.", nameof(metric));
			Destination = destination;
			Netmask = netmask;
			Gateway = gateway;
			Interface = @interface;
			Metric = metric;
		}
コード例 #39
0
 public override int GetHashCode()
 => IpAddress.GetHashCode() ^ MacAddress.GetHashCode();
コード例 #40
0
ファイル: RoutingTable.cs プロジェクト: Clodo76/airvpn-client
        public override void Deactivation()
        {
            base.Deactivation();

            foreach (RouteEntry Entry in EntryAdded.Values)
                Entry.Remove();

            foreach (RouteEntry Entry in EntryRemoved.Values)
            {
                Entry.Add();
                Engine.Instance.Logs.Log(LogType.Verbose, MessagesFormatter.Format(Messages.NetworkLockRouteRestored, Entry.ToString()));
            }

            DefaultGateway = "";
            DefaultInterface = "";

            EntryAdded.Clear();
            EntryRemoved.Clear();
        }
コード例 #41
0
        public ActionResult SubmitAsGuest(Customers _customer, CustomerAddress _address)
        {
            Customers cust = bCustomer.List().Where(m => m.Customers_EmailId == _customer.Customers_EmailId || m.Customers_Phone == _customer.Customers_Phone).FirstOrDefault();

            if (cust == null)
            {
                Customers Customer = new Customers()
                {
                    Customers_FullName      = _customer.Customers_FullName,
                    Customers_Description   = "test description",
                    Customers_EmailId       = _customer.Customers_EmailId,
                    Customers_Phone         = _customer.Customers_Phone,
                    Customers_Photo         = "images/user_icon.png",
                    Customers_Login_Attempt = 0,
                    Customers_CreatedDate   = DateTime.Now,
                    Customers_UpdatedDate   = DateTime.Now,
                    Customers_Password      = _customer.Customers_Password,
                    Customers_Status        = eStatus.Active.ToString(),
                    IsEmailVerified         = 0,
                    CustomerType            = eCustomerType.guest.ToString()
                };

                Customer = bCustomer.Create(Customer);

                if (Convert.ToBoolean(ConfigurationSettings.AppSettings["IsEmailEnable"]))
                {
                    string host = ConfigurationSettings.AppSettings["DomainUrl"].ToString();
                    host = host + "/user/VerifyEmail?VerificationId=" + Customer.CustomerCode + "&reirect-url=ghgfhsgf798798jhshfjsfkjs.html";
                    string body = MailHelper.VerifyEmailLink(host, Customer.Customers_FullName);
                    MailHelper.SendEmail(Customer.Customers_EmailId, "Verify Your EmailId", body, "Rachna Teracotta Store");
                }

                CustomerAddress CustomerAddres = new CustomerAddress()
                {
                    Customer_Id                 = Customer.Customer_Id,
                    Customer_AddressLine1       = _address.Customer_AddressLine1,
                    Customer_AddressLine2       = _address.Customer_AddressLine2,
                    CustomerAddress_LandMark    = _address.CustomerAddress_LandMark,
                    CustomerAddress_City        = _address.CustomerAddress_City,
                    CustomerAddress_State       = _address.CustomerAddress_State,
                    CustomerAddress_Country     = _address.CustomerAddress_Country,
                    CustomerAddress_ZipCode     = _address.CustomerAddress_ZipCode,
                    CustomerAddress_DateCreated = DateTime.Now,
                    CustomerAddress_DateUpdated = DateTime.Now,
                    CustomerAddress_Status      = _address.CustomerAddress_Status
                };

                CustomerAddres = bCustomer.CreateAddress(CustomerAddres);

                Carts _carts = _mcartmdl.GetCarts().Where(m => m.Ip_Address == IpAddress.GetLocalIPAddress() && m.Cart_Status == eCartStatus.Temp.ToString()).FirstOrDefault();
                Session["UserKey"] = Customer.Customer_Id.ToString();
                if (_carts != null)
                {
                    _mcartmdl.SaveCartAfterLogin();
                }
                return(Redirect("/user/paymentmethod"));
            }
            else
            {
                TempData["Message"] = "Oops!! entered customer email/phone already exists.please try with different emailid/phone.";
            }
            return(Redirect("/user/guestcheckin"));
        }
コード例 #42
0
ファイル: RoutingTable.cs プロジェクト: Clodo76/airvpn-client
        public override void OnRecoveryLoad(XmlElement root)
        {
            base.OnRecoveryLoad(root);

            DefaultGateway = root.GetAttribute("gateway");
            DefaultInterface = root.GetAttribute("interface");

            XmlElement nodeAdded = root.GetElementsByTagName("added")[0] as XmlElement;
            foreach (XmlElement nodeEntry in nodeAdded.ChildNodes)
            {
                RouteEntry entry = new RouteEntry();
                entry.ReadXML(nodeEntry);
                EntryAdded[entry.Key] = entry;
            }

            XmlElement nodeRemoved = root.GetElementsByTagName("removed")[0] as XmlElement;
            foreach (XmlElement nodeEntry in nodeRemoved.ChildNodes)
            {
                RouteEntry entry = new RouteEntry();
                entry.ReadXML(nodeEntry);
                EntryRemoved[entry.Key] = entry;
            }
        }
コード例 #43
0
 public override string ToString()
 {
     return(IpAddress.ToString());
 }
コード例 #44
0
ファイル: RoutingTable.cs プロジェクト: Clodo76/airvpn-client
        public void RouteAdd(IpAddress address, IpAddress mask, IpAddress gateway, string iface)
        {
            lock (this)
            {
                string key = RouteEntry.ToKey(address, mask);
                if (EntryAdded.ContainsKey(key))
                {
                    RouteEntry entry = EntryAdded[key];
                    entry.RefCount++;
                }
                else
                {
                    RouteEntry entry = new RouteEntry();
                    entry.Address = address;
                    entry.Mask = mask;
                    entry.Gateway = gateway;
                    entry.Interface = iface;
                    EntryAdded[key] = entry;
                    entry.Add();
                }

                Recovery.Save();
            }
        }
コード例 #45
0
 public IpAddressOperation(Mapping.IpAddressOperation operation, IpAddress ipAddress)
     : base(operation)
 {
     this.IpAddressId = operation.IpAddressId;
     this.IpAddress = ipAddress;
 }
コード例 #46
0
ファイル: RoutingTable.cs プロジェクト: Clodo76/airvpn-client
        public void RouteRemove(IpAddress address, IpAddress mask)
        {
            lock (this)
            {
                string key = RouteEntry.ToKey(address, mask);
                if (EntryAdded.ContainsKey(key))
                {
                    RouteEntry entry = EntryAdded[key];
                    entry.RefCount--;
                    if (entry.RefCount > 0)
                    {
                    }
                    else
                    {
                        entry.Remove();
                        EntryAdded.Remove(key);
                    }
                }

                Recovery.Save();
            }
        }
コード例 #47
0
        public async Task <ProcessResponse> AddIpAddress(IpAddress ipAddress)
        {
            var response = await _ipAddressManagerSystem.AddIpAddress(Mapper.Map <SysData.IpAddress>(ipAddress));

            return(Mapper.Map <ProcessResponse>(response));
        }
コード例 #48
0
ファイル: RoutingTable.cs プロジェクト: Clodo76/airvpn-client
        public override void Activation()
        {
            base.Activation();

            List<RouteEntry> EntryList = Platform.Instance.RouteList();

            DefaultGateway = "";
            DefaultInterface = "";
            EntryRemoved.Clear();
            EntryAdded.Clear();

            foreach (RouteEntry Entry in EntryList)
            {
                if (IsIP(Entry.Gateway))
                {
                    if (DefaultGateway.Valid == false)
                    {
                        DefaultGateway = Entry.Gateway;
                        DefaultInterface = Entry.Interface;
                    }
                    else if (DefaultGateway != Entry.Gateway)
                    {
                        Failed = true;
                        break;
                    }
                }
            }

            if (DefaultGateway.Valid == false)
                Failed = true;

            if (Failed)
            {
                DefaultGateway = "";
                DefaultInterface = "";
                foreach (RouteEntry Entry in EntryList)
                {
                    Engine.Instance.Logs.Log(LogType.Verbose, Entry.ToString());
                }

                throw new Exception("error");
            }

            /*
            foreach (RouteEntry Entry in EntryList)
            {
                if (IsIP(Entry.Gateway))
                {
                    EntryRemoved[Entry.Key] = Entry;
                    Engine.Instance.Logs.Log(LogType.Verbose, Messages.Format(Messages.NetworkLockRouteRemoved, Entry.ToString()));
                    Entry.Remove();
                }
            }
            */

            IpAddress destinationHole = DefaultGateway;
            string interfaceHole = "1";
            int routesHoleN = 4;
            for (int i = 0; i < routesHoleN; i++)
            {
                string maskHole = "192.0.0.0";
                string ipHole = Conversions.ToString((256 / routesHoleN * i)) + ".0.0.0";

                RouteAdd(ipHole, maskHole, destinationHole, interfaceHole);
            }
        }
コード例 #49
0
 public override void AllowIP(IpAddress ip)
 {
     base.AllowIP(ip);
 }
コード例 #50
0
ファイル: ArpPacket.cs プロジェクト: smiley22/Network.Sim
		/// <summary>
		/// Deserializes an ArpPacket instance from the specified sequence of
		/// bytes.
		/// </summary>
		/// <param name="data">The sequence of bytes to deserialize an ArpPacket
		/// object from.</param>
		/// <returns>A deserialized ArpPacket object.</returns>
		public static ArpPacket Deserialize(byte[] data) {
			using (MemoryStream ms = new MemoryStream(data)) {
				using (BinaryReader reader = new BinaryReader(ms)) {
					bool isRequest = reader.ReadBoolean();
					MacAddress macSender = new MacAddress(reader.ReadBytes(6));
					IpAddress ipSender = new IpAddress(reader.ReadBytes(4));
					MacAddress macTarget = new MacAddress(reader.ReadBytes(6));
					IpAddress ipTarget = new IpAddress(reader.ReadBytes(4));
					if (isRequest)
						return new ArpPacket(macSender, ipSender, ipTarget);
					else
						return new ArpPacket(macSender, ipSender, macTarget, ipTarget);
				}
			}
		}
コード例 #51
0
 public override void DeallowIP(IpAddress ip)
 {
     base.DeallowIP(ip);
 }
コード例 #52
0
        public static void SNMPTestConcepto()
        {
            int _NumEntries = 0;

            // SNMP community name
            OctetString community = new OctetString("public");

            // Define agent parameters class
            AgentParameters param = new AgentParameters(community);
            // Set SNMP version to 2 (GET-BULK only works with SNMP ver 2 and 3)
            param.Version = SnmpVersion.Ver2;
            // Construct the agent address object
            // IpAddress class is easy to use here because
            //  it will try to resolve constructor parameter if it doesn't
            //  parse to an IP address
            IpAddress agent = new IpAddress("192.168.1.42");

            // Construct target
            UdpTarget target = new UdpTarget((IPAddress)agent, 161, 2000, 1);

            // Define Oid that is the root of the MIB
            //  tree you wish to retrieve
            //Oid rootOid = new Oid("1.3.6.1.2.1.2.2.1.2"); // ifDescr
            //Oid rootOid = new Oid("1.3.6.1.2.1.17.4.3.1"); // conexiones bridge
            Oid rootOid = new Oid("1.3.6.1.2.1"); // TEST

            // This Oid represents last Oid returned by
            //  the SNMP agent
            Oid lastOid = (Oid)rootOid.Clone();

            // Pdu class used for all requests
            Pdu pdu = new Pdu(PduType.GetBulk);

            // In this example, set NonRepeaters value to 0
            pdu.NonRepeaters = 0;
            // MaxRepetitions tells the agent how many Oid/Value pairs to return
            // in the response.
            pdu.MaxRepetitions = 5;

            // Loop through results
            while (lastOid != null)
            {
                // When Pdu class is first constructed, RequestId is set to 0
                // and during encoding id will be set to the random value
                // for subsequent requests, id will be set to a value that
                // needs to be incremented to have unique request ids for each
                // packet
                if (pdu.RequestId != 0)
                {
                    pdu.RequestId += 1;
                }
                // Clear Oids from the Pdu class.
                pdu.VbList.Clear();
                // Initialize request PDU with the last retrieved Oid
                pdu.VbList.Add(lastOid);
                // Make SNMP request
                SnmpV2Packet result = (SnmpV2Packet)target.Request(pdu, param);
                // You should catch exceptions in the Request if using in real application.

                // If result is null then agent didn't reply or we couldn't parse the reply.
                if (result != null)
                {
                    // ErrorStatus other then 0 is an error returned by
                    // the Agent - see SnmpConstants for error definitions
                    if (result.Pdu.ErrorStatus != 0)
                    {
                        // agent reported an error with the request
                        Console.WriteLine("Error in SNMP reply. Error {0} index {1}",
                            result.Pdu.ErrorStatus,
                            result.Pdu.ErrorIndex);
                        lastOid = null;
                        break;
                    }
                    else
                    {
                        // Walk through returned variable bindings
                        foreach (Vb v in result.Pdu.VbList)
                        {
                            // Check that retrieved Oid is "child" of the root OID
                            if (rootOid.IsRootOf(v.Oid))
                            {
                                Console.WriteLine("{0} ({1}): {2}",
                                    v.Oid.ToString(),
                                    SnmpConstants.GetTypeName(v.Value.Type),
                                    v.Value.ToString());
                                _NumEntries++;

                                if (v.Value.Type == SnmpConstants.SMI_ENDOFMIBVIEW)
                                    lastOid = null;
                                else
                                    lastOid = v.Oid;
                            }
                            else
                            {
                                // we have reached the end of the requested
                                // MIB tree. Set lastOid to null and exit loop
                                lastOid = null;
                            }
                        }
                    }
                }
                else
                {
                    Console.WriteLine("No response received from SNMP agent.");
                }
            }
            target.Close();
            Console.WriteLine("Número entradas: {0}", _NumEntries);
        }
コード例 #53
0
 public bool Equals(IpAddress other)
 {
     return(string.Equals(Address, other.Address) && Port == other.Port);
 }