public void HasIps() { var addresses = IpConfig.ListIpAddresses(); Assert.NotNull(addresses); Assert.NotEmpty(addresses); }
public void HasOnlyIPv4() { var addresses = IpConfig.ListIpV4Addresses(); Assert.NotNull(addresses); Assert.NotEmpty(addresses); }
/// <summary> /// Converts the <see cref="sourceValue" /> parameter to the <see cref="destinationType" /> parameter using <see cref="formatProvider" /// /> and <see cref="ignoreCase" /> /// </summary> /// <param name="sourceValue">the value to convert into an instance of <see cref="IpConfig" />.</param> /// <returns> /// an instance of <see cref="IpConfig" />, or <c>null</c> if there is no suitable conversion. /// </returns> public static object ConvertFrom(dynamic sourceValue) { if (null == sourceValue) { return(null); } try { IpConfig.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString()); } catch { // Unable to use JSON pattern } try { return(new IpConfig { DefaultGatewayIp = sourceValue.DefaultGatewayIp, DhcpOptions = DhcpOptionsTypeConverter.ConvertFrom(sourceValue.DhcpOptions), DhcpServerAddress = AddressTypeConverter.ConvertFrom(sourceValue.DhcpServerAddress), PoolList = sourceValue.PoolList, PrefixLength = sourceValue.PrefixLength, SubnetIp = sourceValue.SubnetIp, }); } catch { } return(null); }
static void StartSearch(App app) { var parameters = new ScanParameters(); var range = IpConfig.IpRangeForIpAddress(IpConfig.ListIpV4Addresses().FirstOrDefault()); parameters.StartIp = range[0]; parameters.LastIp = range[1]; var scanner = new IpScan(); var result = scanner.ScanIpRange(parameters); app.RefreshDeviceList(result); }
public void CheckIpRange() { IPAddress ip, expectedStartIp, expecttedEndIp; ip = IPAddress.Parse("192.168.1.127"); expectedStartIp = IPAddress.Parse("192.168.1.1"); expecttedEndIp = IPAddress.Parse("192.168.1.254"); var result = IpConfig.IpRangeForIpAddress(ip); Assert.NotNull(result); Assert.Equal(2, result.Length); Assert.Equal(expectedStartIp, result[0]); Assert.Equal(expecttedEndIp, result[1]); }
public ActionResult RequestControl(FormCollection form) { IpConfig config = new IpConfig() { }; lock (this) { try { string status = form["ipstatus"]; string[] router = form["address"].ToString().Split(','); XmlDocument xml = new XmlDocument(); string path = HttpContext.Server.MapPath("/App_Data/iptable.xml"); xml.Load(path); xml.SelectSingleNode("root/IpControl").InnerText = status; var routerNode = xml.SelectSingleNode("root/Router"); routerNode.RemoveAll(); foreach (var item in router) { XmlElement xe = xml.CreateElement("Address"); xe.InnerText = item; routerNode.AppendChild(xe); } xml.Save(path); WriteLog($"修改了IP白名单的信息"); _repositoryFactory.SaveChanges(); return(Json(new TipMessage() { Status = true, MsgText = "保存成功!" }, JsonRequestBehavior.DenyGet)); } catch (Exception) { } } return(Json(new TipMessage() { Status = false, MsgText = "保存失败!" }, JsonRequestBehavior.DenyGet)); }
/// <summary> /// Validates that the properties of the given IpConfig make sense logically. /// </summary> /// <param name="ipConfig">The IpConfig to validate.</param> /// <returns>The validated IpConfig.</returns> private IpConfig validateIpConfig(IpConfig ipConfig) { HashSet <string> blocks = new HashSet <string>(); // Check that the IPsPerSub is a power of two if (!((ipConfig.IPsPerSub != 0) && ((ipConfig.IPsPerSub & (ipConfig.IPsPerSub - 1)) == 0))) { // TODO throw new ArgumentException(); } for (int i = 0; i < ipConfig.IpBlocks.Count; i++) { // Remove whitespace from string ipConfig.IpBlocks[i] = Regex.Replace(ipConfig.IpBlocks.ElementAt(i), @"\s+", ""); // Check for duplicate IpBlocks if (!blocks.Add(ipConfig.IpBlocks.ElementAt(i))) { // TODO - One of the IpBlocks is a duplicate throw new ArgumentException(); } // Check that each IpBlock is in valid IPv4 CIDR notation if (!Regex.IsMatch(ipConfig.IpBlocks.ElementAt(i), @"^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])(\/(3[0-2]|[1-2][0-9]|[0-9]))$")) { // TODO throw new ArgumentException(); } int prefix = Int32.Parse(ipConfig.IpBlocks.ElementAt(i).Split('/').ElementAt(1)); // Check to see that there are not more IPsPerSub than available IP addresses if (ipConfig.IPsPerSub > Math.Pow(2, 32 - prefix)) { // TODO throw new ArgumentException(); } } return(ipConfig); }
public ActionResult RequestControl() { IpConfig config = new IpConfig() { }; lock (this) { XmlDocument xml = new XmlDocument(); xml.Load(HttpContext.Server.MapPath("/App_Data/iptable.xml")); config.Status = xml.SelectSingleNode("root/IpControl").InnerText.ToLower(); config.AddressList = new List <string>(); XmlNodeList router = xml.SelectSingleNode("root/Router").ChildNodes; foreach (var item in router) { config.AddressList.Add(((XmlNode)item).InnerText); } } return(View(config)); }
/// <summary> /// Checks to see if the only difference between two IpConfigs is that one /// has additional IpBlocks. If this is not the only difference then an error will /// be thrown. /// </summary> /// <param name="original">The original IpConfig that serves as the baseline.</param> /// <param name="updated">The updated IpConfig that should only have additional IpBlocks.</param> /// <returns>A list of the added IpBlocks.</returns> private List <string> OnlyIpBlocksAdded(IpConfig original, IpConfig updated) { bool same = true; same &= original.Name == updated.Name && original.IPsPerSub == updated.IPsPerSub; for (int i = 0; i < original.IpBlocks.Count; i++) { same &= original.IpBlocks.ElementAt(i) == updated.IpBlocks.ElementAt(i); } if (!same) { // TODO - Some other change was made besides adding IPBlocks throw new NotSupportedException(); } int firstBlockAddedIndex = original.IpBlocks.Count; int numBlocksAdded = updated.IpBlocks.Count - original.IpBlocks.Count; return(updated.IpBlocks.GetRange(firstBlockAddedIndex, numBlocksAdded)); }
/// <summary> /// Trys to assign an IP address to the given subscriptionId. If the IP address is successfully assigned /// then it will be returned. If there are no available IP addresses to assign then an exception /// will be thrown. /// </summary> /// <param name="subscriptionId">The subscriptionId to try to assign an IpAddress to.</param> /// <param name="offerName">The name of the offer the subscription belongs to.</param> /// <param name="ipConfigName">The name of the IpConfig to get an IpAdress from.</param> /// <returns>The assigned IpAddress.</returns> public async Task <IpAddress> TryAssignIpAddress(Guid subscriptionId, string offerName, string ipConfigName) { _logger.LogInformation($"Trying to assign IP addresses to subscription ID {subscriptionId} in offer {offerName} from IP Config {ipConfigName}."); IpConfig ipConfig = await _ipConfigService.GetAsync(offerName, ipConfigName); // We only want to assign IP addresses from IP blocks that belong to the given IP config List <IpBlock> ipBlocks = await _context.IpBlocks.Where(x => x.IpConfigId == ipConfig.Id).ToListAsync(); // Keep track of IpBlock IDs that belong to the IpConfig HashSet <long> blockIds = new HashSet <long>(); foreach (IpBlock ipBlock in ipBlocks) { blockIds.Add(ipBlock.Id); } try { // Find an IpAddress that is available and belongs to one of the IpBlocks we are tracking IpAddress ipAddress = await _context.IpAddresses.Where(x => x.IsAvailable == true && blockIds.Contains(x.IpBlockId)).FirstAsync(); ipAddress.SubscriptionId = subscriptionId; ipAddress.IsAvailable = false; _context.IpAddresses.Update(ipAddress); await _context._SaveChangesAsync(); _logger.LogInformation($"The IP addresses in {ipAddress.Value} have been assigned to subscription ID {subscriptionId}."); return(ipAddress); } catch (ArgumentNullException) { throw new LunaServerException($"There are no IP addresses available in {ipConfigName}."); } }
/// <summary> /// Creates an ipConfig within an offer. /// </summary> /// <param name="offerName">The name of the offer.</param> /// <param name="ipConfig">The ipConfig to create.</param> /// <returns>The created ipConfig.</returns> public async Task <IpConfig> CreateAsync(string offerName, IpConfig ipConfig) { if (ipConfig is null) { throw new LunaBadRequestUserException(LoggingUtils.ComposePayloadNotProvidedErrorMessage(typeof(IpConfig).Name), UserErrorCode.PayloadNotProvided); } // Check that the offer does not already have an ipConfig with the same name if (await ExistsAsync(offerName, ipConfig.Name)) { throw new LunaConflictUserException(LoggingUtils.ComposeAlreadyExistsErrorMessage(typeof(IpConfig).Name, ipConfig.Name, offerName: offerName)); } _logger.LogInformation(LoggingUtils.ComposeCreateResourceMessage(typeof(IpConfig).Name, ipConfig.Name, offerName: offerName, payload: JsonSerializer.Serialize(ipConfig))); // Validate that the values provided for the IpConfig are syntactically and logically correct ipConfig = validateIpConfig(ipConfig); // Get the offer associated with the offerName provided var offer = await _offerService.GetAsync(offerName); // Set the FK to offer ipConfig.OfferId = offer.Id; // Add ipConfig to db _context.IpConfigs.Add(ipConfig); await _context._SaveChangesAsync(); // Process the IpBlocks await ProcessIpBlocks(ipConfig.IpBlocks, ipConfig.Id); _logger.LogInformation(LoggingUtils.ComposeResourceCreatedMessage(typeof(IpConfig).Name, ipConfig.Name, offerName: offerName)); return(ipConfig); }
/// <summary> /// Updates an ipConfig within an offer. /// </summary> /// <param name="offerName">The name of the offer.</param> /// <param name="name">The name of the ipConfig to update.</param> /// <param name="ipConfig">The updated ipConfig.</param> /// <returns>The updated ipConfig.</returns> public async Task <IpConfig> UpdateAsync(string offerName, string name, IpConfig ipConfig) { if (ipConfig is null) { throw new LunaBadRequestUserException(LoggingUtils.ComposePayloadNotProvidedErrorMessage(typeof(Plan).Name), UserErrorCode.PayloadNotProvided); } // Check that that an IpConfig with the given name exists within the Offer if (!(await ExistsAsync(offerName, name))) { throw new LunaNotFoundUserException(LoggingUtils.ComposeNotFoundErrorMessage(typeof(IpConfig).Name, name, offerName: offerName)); } _logger.LogInformation(LoggingUtils.ComposeUpdateResourceMessage(typeof(IpConfig).Name, name, offerName: offerName, payload: JsonSerializer.Serialize(ipConfig))); // Validate that the values provided for the IpConfig are syntactically and logically correct ipConfig = validateIpConfig(ipConfig); // Get the ipConfig that matches the name provided var ipConfigDb = await GetAsync(offerName, name); // Verify that the only change is the addition of new IpBlocks List <string> addedBlocks = OnlyIpBlocksAdded(ipConfigDb, ipConfig); // Process the added IpBlocks await ProcessIpBlocks(addedBlocks, ipConfigDb.Id); // Get the ipConfig from the db again to repopulate the IpBlocks ipConfigDb = await GetAsync(offerName, name); _logger.LogInformation(LoggingUtils.ComposeResourceUpdatedMessage(typeof(IpConfig).Name, name, offerName: offerName)); return(ipConfigDb); }
public async Task <ActionResult> CreateOrUpdateAsync(string offerName, string name, [FromBody] IpConfig ipConfig) { AADAuthHelper.VerifyUserAccess(this.HttpContext, _logger, true); if (ipConfig == null) { throw new LunaBadRequestUserException(LoggingUtils.ComposePayloadNotProvidedErrorMessage(nameof(ipConfig)), UserErrorCode.PayloadNotProvided); } if (!name.Equals(ipConfig.Name)) { throw new LunaBadRequestUserException(LoggingUtils.ComposeNameMismatchErrorMessage(typeof(IpConfig).Name), UserErrorCode.NameMismatch); } if (await _ipConfigService.ExistsAsync(offerName, name)) { _logger.LogInformation($"Update IPConfig {name} in offer {offerName} with payload {JsonSerializer.Serialize(ipConfig)}"); await _ipConfigService.UpdateAsync(offerName, name, ipConfig); return(Ok(ipConfig)); } else { _logger.LogInformation($"Create IPConfig {name} in offer {offerName} with payload {JsonSerializer.Serialize(ipConfig)}"); await _ipConfigService.CreateAsync(offerName, ipConfig); return(CreatedAtRoute(nameof(GetAsync) + nameof(IpConfig), new { offerName = offerName, name = name }, ipConfig)); } }
/*setup timers, connections and variables*/ public UI_NetStatusPanel() { string errmsg = ""; InitializeComponent(); //Setup scalers and controls that must be scaled UIsetup(); _cmdUpdate = Update_CommandUI; _iofeedback = Update_IO_Displays; // Setup the API to use local USB devices if (YAPI.RegisterHub("usb", ref errmsg) != YAPI.SUCCESS) { set_display1("error: " + errmsg); Logging.Add("Cant initiaet Yocto API, do you have another instance running?"); } else { Logging.Add("Yapi Initiated"); } //Set Sensors 1 and 2 sensor1 = YLightSensor.FindLightSensor("L1" + ".lightSensor"); if (sensor1 == null) { set_display1("no L1 sensor"); } else { set_display1("L1 Ok"); } sensor2 = YLightSensor.FindLightSensor("L2" + ".lightSensor"); if (sensor2 == null) { set_display2("no L2 sensor"); Logging.Add("L1 not connected"); } else { set_display2("L2 Ok"); } /*delegates for ui updates*/ _updatedisplay1 = (set_display1); _updatedisplay2 = (set_display2); _updatefeedback = (Update_feedback); _ipConfig = Update_IP_Config; Logic.Initialise_Cameras(); Servlet.Userinterface = this; ///assigning treference to ui for the servlets to conduct updates. This needs to be changed! Logic.Start(); //start a timer _UsbLightReading = new System.Threading.Timer(Lsensor_Tick, null, 0, 1000); //start a timer _NetworkTimer = new System.Threading.Timer(Nmanager.Tick, null, 0, 1000); }