public static Dictionary <string, string> ReturnMatchedIPRange(List <string> ips, List <Value> azureIps) { Dictionary <string, string> matchedIps = new Dictionary <string, string>(); foreach (var ip in ips) { bool ipFound = false; IPNetwork incomingNetwork = null; IPAddress incomingIp = IsValidIP(ip) ? IPAddress.Parse(ip) : null; bool incomingNetworkParsed = incomingIp == null?IPNetwork.TryParse(ip, out incomingNetwork) : false; if (incomingIp != null || incomingNetwork != null) { foreach (var azureip in azureIps) { foreach (var subnet in azureip.properties.addressPrefixes) { IPNetwork network = IPNetwork.Parse(subnet); if (((incomingIp != null && network.Contains(incomingIp)) || (incomingNetwork != null && network.Contains(incomingNetwork))) && !ipFound) { matchedIps.Add(ip, $"{subnet} - {azureip.name}"); ipFound = true; break; } } } if (!ipFound) { if (!matchedIps.ContainsKey(ip)) { matchedIps.Add(ip, "No Match"); } } } else { if (!matchedIps.ContainsKey(ip)) { matchedIps.Add(ip, "No Match"); } } } return(matchedIps); }
public bool AddSrcAddress(IPAddress SrcIP) { IPNetwork localnet192 = IPNetwork.Parse("192.168.0.0/16"); IPNetwork localnet172 = IPNetwork.Parse("172.16.0.0/12"); IPNetwork localnet169 = IPNetwork.Parse("169.254.0.0/16"); IPNetwork localnet10 = IPNetwork.Parse("10.0.0.0/8"); if (SrcIP.IsIPv6LinkLocal || SrcIP.IsIPv6Multicast || SrcIP.IsIPv6SiteLocal || SrcIP.IsIPv6Teredo) { return(false); } if (localnet192.Contains(SrcIP) || localnet172.Contains(SrcIP) || localnet169.Contains(SrcIP) || localnet10.Contains(SrcIP)) { return(false); } if (SrcIP.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork) { IPv4SrcList.Add(SrcIP); } if (SrcIP.AddressFamily == System.Net.Sockets.AddressFamily.InterNetworkV6) { IPv6SrcList.Add(SrcIP); } return(true); }
/// <summary> /// Finds the first network interface that has a matching unicast address- /// </summary> /// <param name="mask">IPv4/IPv6 address or CIDR mask.</param> /// <returns>a matching interface or null</returns> public static NetworkInterface GetNetworkInterfaceFromCIDR(string mask) { if (mask.Contains('/')) { IPNetwork ipnetwork = IPNetwork.Parse(mask); foreach (NetworkInterface nic in GetNetworkInterfaces()) { var unicastAddresses = nic.GetIPProperties().UnicastAddresses; if (unicastAddresses.Any(ua => ipnetwork.Contains(ua.Address))) { return(nic); } } } else { var address = IPAddress.Parse(mask); foreach (NetworkInterface nic in GetNetworkInterfaces()) { var unicastAddresses = nic.GetIPProperties().UnicastAddresses; if (unicastAddresses.Select(ua => ua.Address).Contains(address)) { return(nic); } } } return(null); }
static List <IPNetwork> RecursiveAdd(IPNetwork target, IPNetwork subtract, List <IPNetwork> newNetwork) { if (subtract.Contains(target) || target.Cidr >= 31) { return(newNetwork); } var splitted = Split(target); var firstOverLap = subtract.Overlap(splitted[0]); var secondOverlap = subtract.Overlap(splitted[1]); if (firstOverLap && secondOverlap) { RecursiveAdd(splitted[0], subtract, newNetwork); RecursiveAdd(splitted[1], subtract, newNetwork); } else if (firstOverLap) { newNetwork.Add(splitted[1]); RecursiveAdd(splitted[0], subtract, newNetwork); } else if (secondOverlap) { newNetwork.Add(splitted[0]); RecursiveAdd(splitted[1], subtract, newNetwork); } return(newNetwork); }
public static string ReturnNetwork(string ip) { try { IPAddress incomingIp = IPAddress.Parse(ip); foreach (var subnet in networks) { IPNetwork network = IPNetwork.Parse(subnet); if (network.Contains(incomingIp)) { return(ip); } else { continue; } } } catch (Exception ex) { using (StreamWriter writer = new StreamWriter(log, true)) { while (ex != null) { writer.WriteLine("Message : " + ex.Message + "ip address: " + ip); ex = ex.InnerException; } } } return(string.Empty); }
private async Task FindVnetAndSubnetAsync(CancellationToken cancellationToken) { Debug.Assert(subscriptionId != null); Debug.Assert(resourceGroupName != null); Debug.Assert(targetIPAddress != null); IPAddress virtualMachineIPAddress; if (!IPAddress.TryParse(targetIPAddress, out virtualMachineIPAddress)) { throw new ArgumentException("Invalid format of the IP address"); } var virtualNetworks = (await resourceManager.GetAsync($"/subscriptions/{subscriptionId}/" + $"resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualnetworks", cancellationToken))["value"].ToArray(); foreach (var virtualNetwork in virtualNetworks) { var subnets = virtualNetwork["properties"]["subnets"].ToArray(); foreach (var subnet in subnets) { var addressSpace = subnet["properties"].Value <string>("addressPrefix"); var ipNetwork = IPNetwork.Parse(addressSpace); if (IPNetwork.Contains(ipNetwork, virtualMachineIPAddress)) { virtualNetworkId = virtualNetwork.Value <string>("id"); subnetId = subnet.Value <string>("id"); return; } } } throw new ArgumentException("There is no subnet that contains an IP address " + $"'{virtualMachineIPAddress}' in a resource group '{resourceGroupName}'"); }
private void StartIpBlur(FocusEventArgs e) { if (!IPAddress.TryParse(subnet.StartIP, out IPAddress ipAddress)) { startIpError = true; errorMessage = "The start ip is not valid."; return; } // RFC1918 IPNetwork network1 = IPNetwork.Parse("10.0.0.0/8"); IPNetwork network2 = IPNetwork.Parse("172.16.0.0/12"); IPNetwork network3 = IPNetwork.Parse("192.168.0.0/16"); if (!network1.Contains(ipAddress) && !network2.Contains(ipAddress) && !network3.Contains(ipAddress)) { startIpError = true; errorMessage = "The start ip is not in the range of RFC1918."; return; } subnet.IPRangeId = GetIpRangeId(IPNetwork.Parse($"{subnet.StartIP}/32")); if (subnet.IPRangeId < 0) { startIpError = true; errorMessage = "The start ip is not contained in the virtual network's address spaces."; return; } startIpError = false; errorMessage = string.Empty; }
private bool IsValidIP(string ip) { string[] ranges = new string[] { "167.220.0.0/16", //Boston "131.107.0.0/16", // MS Corp-8 (Redmond) "157.54.0.0/15", // Other MSCorp. ** this list came from Steve Morin. "157.56.0.0/15", "157.58.0.0/15", "157.60.0.0/16", //"0.0.0.0/8", // localhost "::1", // localhosts "73.4.97.83" // comcast //"127.0.0.1" // localhost }; var userIP = IPNetwork.Parse(ip); foreach (string r in ranges) { var range = IPNetwork.Parse(r); if (IPNetwork.Contains(range, userIP)) { return(true); } } return(false); }
/// <summary> /// Gets all unique <c>pairs</c> of hosts with monitoring flag set and which share the same subnet.<br/> /// Subnets with less than or more than two hosts will be discarded. /// </summary> /// <param name="hamnetDbAccess">The handle to access the database.</param> /// <param name="subnet">The subnet to return data for.</param> /// <returns>The dictionary mapping a subnet to its unique monitored host pair.</returns> public static IReadOnlyDictionary <IHamnetDbSubnet, IHamnetDbHosts> UniqueMonitoredHostPairsInSubnet(this IHamnetDbAccess hamnetDbAccess, IPNetwork subnet) { if (hamnetDbAccess == null) { throw new ArgumentNullException(nameof(hamnetDbAccess), "hamnetDbAccess to work with is null"); } if (subnet == null) { throw new ArgumentNullException(nameof(subnet), "subnet search monitored hosts for is null"); } var directSupportHamnetAccess = hamnetDbAccess as IDirectSupportOfHamnetDbAccessExtensions; if (directSupportHamnetAccess != null) { return(directSupportHamnetAccess.UniqueMonitoredHostPairsInSubnet(subnet)); } var hosts = hamnetDbAccess.QueryMonitoredHosts(); var allSubnets = hamnetDbAccess.QuerySubnets(); // filter out parents for which we have nested subnets var subnets = allSubnets.Where(s => !allSubnets.Any(a => !object.ReferenceEquals(s.Subnet, a.Subnet) && s.Subnet.Contains(a.Subnet))); var association = subnets.AssociateHosts(hosts); var uniquePairs = association .Where(a => subnet.Contains(a.Key.Subnet) || subnet.Equals(a.Key.Subnet)) .Where(a => a.Value.Count == 2) .ToDictionary(k => k.Key, v => v.Value); return(uniquePairs); }
public static bool IsIpInRange(string ip, string range) { IPNetwork IpNetwork = IPNetwork.Parse(range); IPAddress incomingIp = IPAddress.Parse(ip); return(IPNetwork.Contains(IpNetwork, incomingIp)); }
public bool IsInSubnet(Subnet source, Subnet toTest) { IPNetwork sourceSubnet = IPNetwork.Parse(source.IPAddress, source.Cidr); IPNetwork testSubnet = IPNetwork.Parse(toTest.IPAddress, toTest.Cidr); return(sourceSubnet.Contains(testSubnet)); }
private void AddListenIpToList() { string hostName = Dns.GetHostName(); var addressList = Dns.GetHostAddresses(hostName); IPNetwork localnet192 = IPNetwork.Parse("192.168.0.0/16"); IPNetwork localnet172 = IPNetwork.Parse("172.16.0.0/12"); IPNetwork localnet169 = IPNetwork.Parse("169.254.0.0/16"); IPNetwork localnet10 = IPNetwork.Parse("10.0.0.0/8"); foreach (IPAddress ip in addressList.Distinct().ToList()) { if (ip.IsIPv6LinkLocal || ip.IsIPv6Multicast || ip.IsIPv6SiteLocal || ip.IsIPv6Teredo) { continue; } if (localnet192.Contains(ip) || localnet172.Contains(ip) || localnet169.Contains(ip) || localnet10.Contains(ip)) { continue; } if (ip.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork) { listListenIP.Items.Add(ip); } if (ip.AddressFamily == System.Net.Sockets.AddressFamily.InterNetworkV6) { listListenIP.Items.Add(ip); } } }
private static void ContainNetwork(ProgramContext ac) { foreach (IPNetwork ipnetwork in ac.Networks) { bool contain = IPNetwork.Contains(ac.ContainNetwork, ipnetwork); Console.WriteLine("{0} contains {1} : {2}", ac.ContainNetwork, ipnetwork, contain); } }
private async Task StartIpBlur(IPRange ipRange) { bool validIp = IPAddress.TryParse(ipRange.StartIpHolder, out IPAddress ipAddress); if (!validIp) { ipRange.IpInvalidMessage = "Network IP address is not valid."; ipRange.HolderIpInvalid = !validIp; return; } // RFC1918 IPNetwork network1 = IPNetwork.Parse("10.0.0.0/8"); IPNetwork network2 = IPNetwork.Parse("172.16.0.0/12"); IPNetwork network3 = IPNetwork.Parse("192.168.0.0/16"); if (!network1.Contains(ipAddress) && !network2.Contains(ipAddress) && !network3.Contains(ipAddress)) { ipRange.IpInvalidMessage = $"Network IP address is not recommended. " + $"<a href=\"https://docs.microsoft.com/en-us/azure/virtual-network/virtual-networks-faq#what-address-ranges-can-i-use-in-my-vnets\" target=\"_blank\">More info</a>"; ipRange.HolderIpInvalid = true; return; } ipRange.HolderIpInvalid = false; ipRange.IpInvalidMessage = string.Empty; var subnets = _vnet.Subnets.Where(s => s.IPRangeId == ipRange.Id).ToList(); if (subnets.Count > 0 && ipRange.StartIpHolder != ipRange.StartIP) { // Too complex to sort out new addresses for all subnets. So reset them. var content = "Chaning network IP will reset all its subnets!"; var title = "Warning"; var confirmResult = await _confirmService.Show(content, title, ConfirmButtons.OKCancel, ConfirmIcon.Warning, new ConfirmButtonOptions() { Button1Props = new ButtonProps() { Type = "primary", Danger = true } }); if (confirmResult == ConfirmResult.OK) { _vnet.SetVnetStartIp(ipRange.Id, ipRange.StartIpHolder); _vnet.ResetSubnets(ipRange.Id); } } else { _vnet.SetVnetStartIp(ipRange.Id, ipRange.StartIpHolder); } ipRange.StartIpHolder = ipRange.StartIP; }
public static bool IsAllowed(HttpContext context) { var ip = GetIpAddress(context); var userIsOnEsportsNetwork = IPNetwork.Contains(EsportsNetwork, IPAddress.Parse(ip)); var userIsOnEduroamNetwork = IPNetwork.Contains(EduroamNetwork, IPAddress.Parse(ip)); var userIsLocalhost = IPNetwork.Contains(LocalhostNetwork, IPAddress.Parse(ip)); var userIsLocalhostIPv6 = IPNetwork.Contains(LocalhostNetworkIPv6, IPAddress.Parse(ip)); return(userIsOnEsportsNetwork || userIsOnEduroamNetwork || userIsLocalhost || userIsLocalhostIPv6); }
/// <summary> /// 2 개의 IP 를 비교하여 ipAddr2 가 ipAddr1 에 속하는지 여부를 반환합니다. /// </summary> /// <param name="ipAddr1">기준이 되는 Ip Addr</param> /// <param name="ipAddr2">ipAddr1 에 종속되는 ip 인지 확인할 Ip Addr</param> /// <returns>ture : ipAddr2 가 ipAddr1 에 종속 / false : ipAddr2 가 ipAddr1 에 종속되지 않음</returns> public static bool ValidationIpAddresInGroup(string ipAddr1, string ipAddr2) { bool returnResult = false; IPNetwork ipnetwork = IPNetwork.Parse(ipAddr1 + "/24"); IPAddress ipaddress = IPAddress.Parse(ipAddr2); returnResult = IPNetwork.Contains(ipnetwork, ipaddress); return(returnResult); }
/// <summary> /// Localiza la ip /// </summary> /// <param name="address">Direccón</param> public GeoLocateResult LocateIp(IPAddress address) { foreach (geoIp g in _Locates) { if (IPNetwork.Contains(g.Network, address)) { return(g.Result); } } return(GeoLocateResult.Empty); }
public static bool ValidaRangoIPV4(string ipDir, string dirRed, string cidr) { string rango = dirRed + cidr; IPNetwork ipnetwork = IPNetwork.Parse(rango); IPAddress ipaddress = IPAddress.Parse(ipDir); IPAddress ipaddress2 = IPAddress.Parse("192.168.0.200"); #pragma warning disable CS0618 // El tipo o el miembro están obsoletos bool contains = IPNetwork.Contains(ipnetwork, ipaddress); #pragma warning restore CS0618 // El tipo o el miembro están obsoletos return(contains); }
public static bool ValidaRangoIPV6(string ipDir, string dirRed, string cidr) { string rango = dirRed + cidr; IPNetwork ipnetwork = IPNetwork.Parse(rango); IPAddress ipaddress = IPAddress.Parse(ipDir); IPAddress ipaddress2 = IPAddress.Parse("fe80::202:b3ff:fe1e:1"); #pragma warning disable CS0618 // El tipo o el miembro están obsoletos Ignoramos la advertencia del compilador bool contains = IPNetwork.Contains(ipnetwork, ipaddress); #pragma warning restore CS0618 // El tipo o el miembro están obsoletos return(contains); }
public void ParseTest() { //http://www.subnet-calculator.com/cidr.php //IPNetwork mynetwork = new IPNetwork(); IPNetwork ipnetwork = IPNetwork.Parse("198.169.76.64/26"); IPAddress ipaddress = IPAddress.Parse("198.169.76.75"); //198.238.108.200 bool result = IPNetwork.Contains(ipnetwork, ipaddress); bool expected = true; Assert.AreEqual(expected, result, "contains"); }
public static bool IsCloudFlareIP(string ip) { foreach (string block in CloudFlareIPRanges) { IPNetwork network = IPNetwork.Parse(block); if (IPNetwork.Contains(network, IPAddress.Parse(ip))) { return(true); } } return(false); }
public static bool IsBlocked(string ip) { IPAddress ipAddress; if (ip != null && ip == "::1") { ip = "127.0.0.1"; } if (IPAddress.TryParse(ip, out ipAddress)) { return(BlockedIpList.Any(n => IPNetwork.Contains(n, ipAddress))); } return(true); }
public static bool IsIpNat(string ip) { IPAddress incomingIp = IPAddress.Parse(ip); foreach (var subnet in IpBlocks) { IPNetwork network = IPNetwork.Parse(subnet); if (IPNetwork.Contains(network, incomingIp)) { return(true); } } return(false); }
public static bool IsUserIpWhiteListed(string userIp, string acl) { var aclList = acl.Split(',').ToList(); //try for a exact IP match if (aclList.Contains(userIp) || userIp == "127.0.0.1") { return(true); } //try for a network match by CIDR notation; i.e. 10.0.0.0/8 var networkList = aclList.Where(x => x.Contains('/')); return(networkList.Any(x => IPNetwork.Contains(IPNetwork.Parse(x), IPAddress.Parse(userIp)))); }
private static string DetermineIPv4AddressType(IPAddress address) { if (MulticastNetwork.Contains(address)) { return("multicast"); } else if (PrivateUseNetworks.Any(network => network.Contains(address))) { return("private"); } else { return("public"); } }
public string GetRegionNameByIpOrUrl(string ipOrUrl, string ipFilePath = null) { if (string.IsNullOrEmpty(ipOrUrl)) { return("Must specify a valid ipAddress or url"); } if (string.IsNullOrEmpty(ipFilePath)) { ipFilePath = HostingEnvironment.MapPath("~/App_Data/"); } if (!(ipOrUrl.StartsWith("http://") || ipOrUrl.StartsWith("https://"))) { ipOrUrl = "http://" + ipOrUrl; } Uri tmp = new Uri(ipOrUrl); ipOrUrl = tmp.Host; var sw = new Stopwatch(); sw.Start(); try { var ips = Dns.GetHostAddresses(ipOrUrl); var ipAddr = ips[0]; var subnets = SubnetBuilder.GetSubnetDictionary(ipFilePath); foreach (IPNetwork net in subnets.Keys) { if (IPNetwork.Contains(net, ipAddr)) { var regionAlias = subnets[net]; sw.Stop(); string region = AzureSpeedData.RegionNames[regionAlias]; logger.Info("IpOrUrl = {0}, region = {1}, time = {2}", ipOrUrl, region, sw.ElapsedMilliseconds); return(region); } } } catch (Exception ex) { logger.Error(ex); return("Invalid Address!"); } return("Region not found"); }
public static bool IpIsWithinCloudfareIPRange(string ip) { IPAddress incomingIp = IPAddress.Parse(ip); var cache = new CloudfareIPCache(); var range = (List <IPNetwork>)cache.Get(); foreach (var network in range) { if (IPNetwork.Contains(network, incomingIp)) { return(true); } } return(false); }
private static IPAddress GetLocalIpAddress(IPNetwork localNetwork) { var host = Dns.GetHostEntry(Dns.GetHostName()); foreach (var ip in host.AddressList) { if (localNetwork.Contains(ip)) { return(ip); } //if (IPNetwork.Contains(localNetwork, ip)) //{ // return ip; //} } throw new Exception("Local IP Address Not Found!"); }
/// <summary> /// Checks whether two ip ranges (networks) overlap. /// </summary> public static bool CIDROverlaps(string cidr1, string cidr2) { IPNetwork net1 = IPNetwork.Parse(cidr1); IPNetwork net2 = IPNetwork.Parse(cidr2); bool net1Contains = IPNetwork.Contains(net1, net2.Network) || IPNetwork.Contains(net1, net2.Broadcast); bool net2Contains = IPNetwork.Contains(net2, net1.Network) || IPNetwork.Contains(net2, net1.Broadcast); if (net1Contains || net2Contains) { return(true); } else { return(false); } }
public Guid GetLocationIdByIp(string ip) { IPAddress ipAddress; if (!IPAddress.TryParse(ip, out ipAddress)) { return(Guid.Empty); } var networks = _locationRepository.GetAllLocationNetworks().Where(n => n.Network.AddressFamily == ipAddress.AddressFamily); Guid match = networks .Where(n => IPNetwork.Contains(n.Network, ipAddress)) .OrderByDescending(n => n.Cidr) .Select(n => n.Id) .FirstOrDefault(); return(match); }