public static unsafe bool Ipv4StringToAddress(ReadOnlySpan <char> ipSpan, out long address) { int end = ipSpan.Length; long tmpAddr; fixed(char *ipStringPtr = &MemoryMarshal.GetReference(ipSpan)) { tmpAddr = IPv4AddressHelper.ParseNonCanonical(ipStringPtr, 0, ref end, notImplicitFile: true); } if (tmpAddr != IPv4AddressHelper.Invalid && end == ipSpan.Length) { // IPv4AddressHelper.ParseNonCanonical returns the bytes in the inverse order. // Reverse them and return success. address = ((0xFF000000 & tmpAddr) >> 24) | ((0x00FF0000 & tmpAddr) >> 8) | ((0x0000FF00 & tmpAddr) << 8) | ((0x000000FF & tmpAddr) << 24); return(true); } else { // Failed to parse the address. address = 0; return(false); } }
public static unsafe bool Ipv4StringToAddress(string ipString, out long address) { Debug.Assert(ipString != null); long tmpAddr; int end = ipString.Length; fixed(char *ipStringPtr = ipString) { tmpAddr = IPv4AddressHelper.ParseNonCanonical(ipStringPtr, 0, ref end, notImplicitFile: true); } if (tmpAddr != IPv4AddressHelper.Invalid && end == ipString.Length) { // IPv4AddressHelper.ParseNonCanonical returns the bytes in the inverse order. // Reverse them and return success. address = ((0xFF000000 & tmpAddr) >> 24) | ((0x00FF0000 & tmpAddr) >> 8) | ((0x0000FF00 & tmpAddr) << 8) | ((0x000000FF & tmpAddr) << 24); return(true); } else { // Failed to parse the address. address = 0; return(false); } }
public static string ConvertCidrToSubnetmask(int cidr) { string bits = string.Empty; for (int i = 0; i < cidr; i++) { bits += "1"; } return(IPv4AddressHelper.BinaryStringToHumanString(bits.PadRight(32, '0'))); }
public override ValidationResult Validate(object value, CultureInfo cultureInfo) { bool isValid = true; foreach (string ipOrRange in (value as string).Replace(" ", "").Split(';')) { if (Regex.IsMatch(ipOrRange, RegexHelper.IPv4AddressRegex)) { continue; } if (Regex.IsMatch(ipOrRange, RegexHelper.IPv4AddressCidrRegex)) { continue; } if (Regex.IsMatch(ipOrRange, RegexHelper.IPv4AddressSubnetmaskRegex)) { continue; } if (Regex.IsMatch(ipOrRange, RegexHelper.IPv4AddressRangeRegex)) { string[] range = ipOrRange.Split('-'); if (IPv4AddressHelper.ConvertToInt32(IPAddress.Parse(range[0])) >= IPv4AddressHelper.ConvertToInt32(IPAddress.Parse(range[1]))) { isValid = false; } } else { isValid = false; } } if (isValid) { return(ValidationResult.ValidResult); } else { return(new ValidationResult(false, Application.Current.Resources["String_ValidateError_EnterValidIPScanRange"] as string)); } }
public static SubnetInfo CalculateIPv4Subnet(IPAddress ipv4Address, IPAddress subnetmask) { IPAddress networkAddress = SubnetHelper.GetIPv4NetworkAddress(ipv4Address, subnetmask); IPAddress broadcast = SubnetHelper.GetIPv4Broadcast(ipv4Address, subnetmask); int cidr = SubnetmaskHelper.ConvertSubnetmaskToCidr(subnetmask); int totalIPs = SubnetmaskHelper.GetNumberIPv4Addresses(cidr); return(new SubnetInfo { NetworkAddress = networkAddress, Broadcast = broadcast, TotalIPs = totalIPs, Subnetmask = subnetmask, CIDR = cidr, HostFirstIP = IPv4AddressHelper.IncrementIPv4Address(networkAddress, 1), HostLastIP = IPv4AddressHelper.DecrementIPv4Address(broadcast, 1), HostIPs = totalIPs - 2 }); }
public static SubnetInfo CalculateIPv4Subnet(IPAddress ipv4Address, IPAddress subnetmask) { IPAddress networkAddress = GetIPv4NetworkAddress(ipv4Address, subnetmask); IPAddress broadcast = GetIPv4Broadcast(ipv4Address, subnetmask); int cidr = Subnetmask.ConvertSubnetmaskToCidr(subnetmask); long totalIPs = Subnetmask.GetNumberIPv4Addresses(cidr); // Fix bug when /31 (host first/last can be null) IPAddress hostFirstIP = null; IPAddress hostLastIP = null; long hostIPs = 0; if (totalIPs == 1) // Fix bug when /32 (show range for 1 IP) { hostFirstIP = networkAddress; hostLastIP = broadcast; hostIPs = 0; } else if (totalIPs > 2) // Calculate for /0-/30 { hostFirstIP = IPv4AddressHelper.IncrementIPv4Address(networkAddress, 1); hostLastIP = IPv4AddressHelper.DecrementIPv4Address(broadcast, 1); hostIPs = totalIPs - 2; } return(new SubnetInfo { NetworkAddress = networkAddress, Broadcast = broadcast, IPAddresses = totalIPs, Subnetmask = subnetmask, CIDR = cidr, HostFirstIP = hostFirstIP, HostLastIP = hostLastIP, Hosts = hostIPs }); }
public static unsafe bool Ipv4StringToAddress(ReadOnlySpan <char> ipSpan, out long address) { int end = ipSpan.Length; long tmpAddr; fixed(char *ipStringPtr = &MemoryMarshal.GetReference(ipSpan)) { tmpAddr = IPv4AddressHelper.ParseNonCanonical(ipStringPtr, 0, ref end, notImplicitFile: true); } if (tmpAddr != IPv4AddressHelper.Invalid && end == ipSpan.Length) { // IPv4AddressHelper.ParseNonCanonical returns the bytes in host order. // Convert to network order and return success. address = (uint)IPAddress.HostToNetworkOrder(unchecked ((int)tmpAddr)); return(true); } else { // Failed to parse the address. address = 0; return(false); } }
public override ValidationResult Validate(object value, CultureInfo cultureInfo) { bool isValid = true; foreach (string ipOrRange in (value as string).Replace(" ", "").Split(';')) { // like 192.168.0.1 if (Regex.IsMatch(ipOrRange, RegexHelper.IPv4AddressRegex)) { continue; } // like 192.168.0.0/24 if (Regex.IsMatch(ipOrRange, RegexHelper.IPv4AddressCidrRegex)) { continue; } // like 192.168.0.0/255.255.255.0 if (Regex.IsMatch(ipOrRange, RegexHelper.IPv4AddressSubnetmaskRegex)) { continue; } // like 192.168.0.0 - 192.168.0.100 if (Regex.IsMatch(ipOrRange, RegexHelper.IPv4AddressRangeRegex)) { string[] range = ipOrRange.Split('-'); if (IPv4AddressHelper.ConvertToInt32(IPAddress.Parse(range[0])) >= IPv4AddressHelper.ConvertToInt32(IPAddress.Parse(range[1]))) { isValid = false; } continue; } // like 192.168.[50-100].1 if (Regex.IsMatch(ipOrRange, RegexHelper.IPv4AddressSpecialRangeRegex)) { string[] octets = ipOrRange.Split('.'); foreach (string octet in octets) { // Match [50-100] if (Regex.IsMatch(octet, RegexHelper.SpecialRangeRegex)) { foreach (string numberOrRange in octet.Substring(1, octet.Length - 2).Split(',')) { if (numberOrRange.Contains("-")) { // 50-100 --> {50, 100} string[] rangeNumber = numberOrRange.Split('-'); if (int.Parse(rangeNumber[0]) > int.Parse(rangeNumber[1])) { isValid = false; } } } } } continue; } isValid = false; } if (isValid) { return(ValidationResult.ValidResult); } else { return(new ValidationResult(false, Application.Current.Resources["String_ValidateError_EnterValidIPScanRange"] as string)); } }
private static IPAddress InternalParse(string ipString, bool tryParse) { if (ipString == null) { if (tryParse) { return(null); } throw new ArgumentNullException("ipString"); } // // IPv6 Changes: Detect probable IPv6 addresses and use separate // parse method. // if (ipString.IndexOf(':') != -1) { #if !FEATURE_PAL // // If the address string contains the colon character // then it can only be an IPv6 address. Use a separate // parse method to unpick it all. Note: we don't support // port specification at the end of address and so can // make this decision. // // We need to make sure that Socket is initialized for this // call ! // SocketException e = null; long scope = 0; if (Socket.OSSupportsIPv6) { byte[] bytes = new byte[IPv6AddressBytes]; SocketAddress saddr = new SocketAddress(AddressFamily.InterNetworkV6, SocketAddress.IPv6AddressSize); SocketError errorCode = UnsafeNclNativeMethods.OSSOCK.WSAStringToAddress( ipString, AddressFamily.InterNetworkV6, IntPtr.Zero, saddr.m_Buffer, ref saddr.m_Size); if (errorCode == SocketError.Success) { // // We have to set up the address by hand now, to avoid initialization // recursion problems that we get if we use IPEndPoint.Create. // for (int i = 0; i < IPv6AddressBytes; i++) { bytes[i] = saddr[i + 8]; } // // Scope // scope = (long)((saddr[27] << 24) + (saddr[26] << 16) + (saddr[25] << 8) + (saddr[24])); return(new IPAddress(bytes, scope)); } if (tryParse) { return(null); } e = new SocketException(); } else { unsafe { int offset = 0; if (ipString[0] != '[') { ipString = ipString + ']'; //for Uri parser to find the terminator. } else { offset = 1; } int end = ipString.Length; fixed(char *name = ipString) { if (IPv6AddressHelper.IsValidStrict(name, offset, ref end) || (end != ipString.Length)) { ushort[] numbers = new ushort[NumberOfLabels]; string scopeId = null; fixed(ushort *numbPtr = numbers) { IPv6AddressHelper.Parse(ipString, numbPtr, 0, ref scopeId); } // // Scope // if (scopeId == null || scopeId.Length == 0) { return(new IPAddress(numbers, 0)); } uint result; scopeId = scopeId.Substring(1); if (UInt32.TryParse(scopeId, NumberStyles.None, null, out result)) { return(new IPAddress(numbers, result)); } } } } if (tryParse) { return(null); } e = new SocketException(SocketError.InvalidArgument); } throw new FormatException(SR.GetString(SR.dns_bad_ip_address), e); #else // !FEATURE_PAL // IPv6 addresses not supported for FEATURE_PAL throw new SocketException(SocketError.OperationNotSupported); #endif // !FEATURE_PAL } else // The new IPv4 parser is better than the native one, it can parse 0xFFFFFFFF. (It's faster too). { // App-Compat: The .NET 4.0 parser used Winsock. When we removed this initialization in 4.5 it // uncovered bugs in IIS's management APIs where they failed to initialize Winsock themselves. // DDCC says we need to keep this for an in place release, but to remove it in the next SxS release. Socket.InitializeSockets(); /////////////////////////// int end = ipString.Length; long result; unsafe { fixed(char *name = ipString) { result = IPv4AddressHelper.ParseNonCanonical(name, 0, ref end, true); } } if (result == IPv4AddressHelper.Invalid || end != ipString.Length) { if (tryParse) { return(null); } throw new FormatException(SR.GetString(SR.dns_bad_ip_address)); } // IPv4AddressHelper always returns IP address in a format that we need to reverse. result = (((result & 0x000000FF) << 24) | (((result & 0x0000FF00) << 8) | (((result & 0x00FF0000) >> 8) | ((result & 0xFF000000) >> 24)))); return(new IPAddress(result)); } } // Parse
// // IsValid // // Determine whether a name is a valid IPv6 address. Rules are: // // * 8 groups of 16-bit hex numbers, separated by ':' // * a *single* run of zeros can be compressed using the symbol '::' // * an optional string of a ScopeID delimited by '%' // * an optional (last) 1 or 2 character prefix length field delimited by '/' // * the last 32 bits in an address can be represented as an IPv4 address // // Inputs: // <argument> name // Domain name field of a URI to check for pattern match with // IPv6 address // // Outputs: // Nothing // // Assumes: // the correct name is terminated by ']' character // // Returns: // true if <name> has IPv6 format, else false // // Throws: // Nothing // // Remarks: MUST NOT be used unless all input indexes are are verified and trusted. // start must be next to '[' position, or error is reported internal unsafe static bool IsValid(char *name, int start, ref int end) { int sequenceCount = 0; int sequenceLength = 0; bool haveCompressor = false; bool haveIPv4Address = false; bool havePrefix = false; bool expectingNumber = true; int lastSequence = 1; int i; for (i = start; i < end; ++i) { if (havePrefix ? (name[i] >= '0' && name[i] <= '9') : Uri.IsHexDigit(name[i])) { ++sequenceLength; expectingNumber = false; } else { if (sequenceLength > 4) { return(false); } if (sequenceLength != 0) { ++sequenceCount; lastSequence = i - sequenceLength; } switch (name[i]) { case '%': while (true) { //accept anything in scopeID if (++i == end) { // no closing ']', fail return(false); } if (name[i] == ']') { goto case ']'; } else if (name[i] == '/') { goto case '/'; } } case ']': start = i; i = end; //this will make i = end+1 continue; case ':': if ((i > 0) && (name[i - 1] == ':')) { if (haveCompressor) { // // can only have one per IPv6 address // return(false); } haveCompressor = true; expectingNumber = false; } else { expectingNumber = true; } break; case '/': if ((sequenceCount == 0) || havePrefix) { return(false); } havePrefix = true; expectingNumber = true; break; case '.': if (haveIPv4Address) { return(false); } i = end; if (!IPv4AddressHelper.IsValid(name, lastSequence, ref i, true, false)) { return(false); } // ipv4 address takes 2 slots in ipv6 address, one was just counted meeting the '.' ++sequenceCount; haveIPv4Address = true; --i; // it will be incremented back on the next loop break; default: return(false); } sequenceLength = 0; } } // // if the last token was a prefix, check number of digits // if (havePrefix && ((sequenceLength < 1) || (sequenceLength > 2))) { return(false); } // // these sequence counts are -1 because it is implied in end-of-sequence // int expectedSequenceCount = 8 + (havePrefix ? 1 : 0); if (!expectingNumber && (sequenceLength <= 4) && (haveCompressor ? (sequenceCount < expectedSequenceCount) : (sequenceCount == expectedSequenceCount))) { if (i == end + 1) { // ']' was found end = start + 1; return(true); } return(false); } return(false); }
// // Parse // // Convert this IPv6 address into a sequence of 8 16-bit numbers // // Inputs: // <member> Name // The validated IPv6 address // // Outputs: // <member> numbers // Array filled in with the numbers in the IPv6 groups // // <member> PrefixLength // Set to the number after the prefix separator (/) if found // // Assumes: // <Name> has been validated and contains only hex digits in groups of // 16-bit numbers, the characters ':' and '/', and a possible IPv4 // address // // Returns: // true if this is a loopback, false otherwise. There is no falure indication as the sting must be a valid one. // // Throws: // Nothing // unsafe internal static bool Parse(string address, ushort *numbers, int start, ref string scopeId) { int number = 0; int index = 0; int compressorIndex = -1; bool numberIsValid = true; //This used to be a class instance member but have not been used so far int PrefixLength = 0; if (address[start] == '[') { ++start; } for (int i = start; i < address.Length && address[i] != ']';) { switch (address[i]) { case '%': if (numberIsValid) { numbers[index++] = (ushort)number; numberIsValid = false; } start = i; for (++i; address[i] != ']' && address[i] != '/'; ++i) { ; } scopeId = address.Substring(start, i - start); // ignore prefix if any for (; address[i] != ']'; ++i) { ; } break; case ':': numbers[index++] = (ushort)number; number = 0; ++i; if (address[i] == ':') { compressorIndex = index; ++i; } else if ((compressorIndex < 0) && (index < 6)) { // // no point checking for IPv4 address if we don't // have a compressor or we haven't seen 6 16-bit // numbers yet // break; } // // check to see if the upcoming number is really an IPv4 // address. If it is, convert it to 2 ushort numbers // for (int j = i; (address[j] != ']') && (address[j] != ':') && (address[j] != '%') && (address[j] != '/') && (j < i + 4); ++j) { if (address[j] == '.') { // // we have an IPv4 address. Find the end of it: // we know that since we have a valid IPv6 // address, the only things that will terminate // the IPv4 address are the prefix delimiter '/' // or the end-of-string (which we conveniently // delimited with ']') // while ((address[j] != ']') && (address[j] != '/') && (address[j] != '%')) { ++j; } number = IPv4AddressHelper.ParseHostNumber(address, i, j); numbers[index++] = (ushort)(number >> 16); numbers[index++] = (ushort)number; i = j; // // set this to avoid adding another number to // the array if there's a prefix // number = 0; numberIsValid = false; break; } } break; case '/': if (numberIsValid) { numbers[index++] = (ushort)number; numberIsValid = false; } // // since we have a valid IPv6 address string, the prefix // length is the last token in the string // for (++i; address[i] != ']'; ++i) { PrefixLength = PrefixLength * 10 + (address[i] - '0'); } break; default: number = number * 16 + Uri.FromHex(address[i++]); break; } } // // add number to the array if its not the prefix length or part of // an IPv4 address that's already been handled // if (numberIsValid) { numbers[index++] = (ushort)number; } // // if we had a compressor sequence ("::") then we need to expand the // numbers array // if (compressorIndex > 0) { int toIndex = NumberOfLabels - 1; int fromIndex = index - 1; for (int i = index - compressorIndex; i > 0; --i) { numbers[toIndex--] = numbers[fromIndex]; numbers[fromIndex--] = 0; } } // // is the address loopback? Loopback is defined as one of: // // 0:0:0:0:0:0:0:1 // 0:0:0:0:0:0:127.0.0.1 == 0:0:0:0:0:0:7F00:0001 // 0:0:0:0:0:FFFF:127.0.0.1 == 0:0:0:0:0:FFFF:7F00:0001 // return(((numbers[0] == 0) && (numbers[1] == 0) && (numbers[2] == 0) && (numbers[3] == 0) && (numbers[4] == 0)) && (((numbers[5] == 0) && (numbers[6] == 0) && (numbers[7] == 1)) || (((numbers[6] == 0x7F00) && (numbers[7] == 0x0001)) && ((numbers[5] == 0) || (numbers[5] == 0xFFFF))))); }
public static List <ARPTableInfo> GetTable() { List <ARPTableInfo> list = new List <ARPTableInfo>(); // The number of bytes needed. int bytesNeeded = 0; // The result from the API call. int result = GetIpNetTable(IntPtr.Zero, ref bytesNeeded, false); // Call the function, expecting an insufficient buffer. if (result != ERROR_INSUFFICIENT_BUFFER) { // Throw an exception. throw new Win32Exception(result); } // Allocate the memory, do it in a try/finally block, to ensure // that it is released. IntPtr buffer = IntPtr.Zero; // Try/finally. try { // Allocate the memory. buffer = Marshal.AllocCoTaskMem(bytesNeeded); // Make the call again. If it did not succeed, then // raise an error. result = GetIpNetTable(buffer, ref bytesNeeded, false); // If the result is not 0 (no error), then throw an exception. if (result != 0) { // Throw an exception. throw new Win32Exception(result); } // Now we have the buffer, we have to marshal it. We can read // the first 4 bytes to get the length of the buffer. int entries = Marshal.ReadInt32(buffer); // Increment the memory pointer by the size of the int. IntPtr currentBuffer = new IntPtr(buffer.ToInt64() + Marshal.SizeOf(typeof(int))); // Allocate an array of entries. MIB_IPNETROW[] table = new MIB_IPNETROW[entries]; // Cycle through the entries. for (int i = 0; i < entries; i++) { // Call PtrToStructure, getting the structure information. table[i] = (MIB_IPNETROW)Marshal.PtrToStructure(new IntPtr(currentBuffer.ToInt64() + (i * Marshal.SizeOf(typeof(MIB_IPNETROW)))), typeof(MIB_IPNETROW)); } PhysicalAddress virtualMAC = new PhysicalAddress(new byte[] { 0, 0, 0, 0, 0, 0 }); PhysicalAddress broadcastMAC = new PhysicalAddress(new byte[] { 255, 255, 255, 255, 255, 255 }); for (int i = 0; i < entries; i++) { MIB_IPNETROW row = table[i]; IPAddress ipAddress = new IPAddress(BitConverter.GetBytes(row.dwAddr)); PhysicalAddress macAddress = new PhysicalAddress(new byte[] { row.mac0, row.mac1, row.mac2, row.mac3, row.mac4, row.mac5 }); // Filter 0.0.0.0.0.0, 255.255.255.255.255.255 if (!macAddress.Equals(virtualMAC) && !macAddress.Equals(broadcastMAC)) { list.Add(new ARPTableInfo(ipAddress, macAddress, (ipAddress.IsIPv6Multicast || IPv4AddressHelper.IsMulticast(ipAddress)))); } } return(list); } finally { // Release the memory. FreeMibTable(buffer); } }
public static int ConvertSubnetmaskToCidr(IPAddress subnetmask) { return(string.Join("", IPv4AddressHelper.HumanStringToBinaryString(subnetmask.ToString()).Replace(".", "").TrimEnd('0')).Length); }
private static unsafe bool InternalIsValid(char *name, int start, ref int end, bool validateStrictAddress) { int num = 0; int num2 = 0; bool flag = false; bool flag2 = false; bool flag3 = false; bool flag4 = true; int num3 = 1; int index = start; while (index < end) { if (flag3 ? ((name[index] >= '0') && (name[index] <= '9')) : Uri.IsHexDigit(name[index])) { num2++; flag4 = false; goto Label_013F; } if (num2 <= 4) { if (num2 != 0) { num++; num3 = index - num2; } switch (name[index]) { case ':': if ((index <= 0) || (name[index - 1] != ':')) { goto Label_00F9; } if (flag) { return(false); } flag = true; flag4 = false; goto Label_013D; case ']': goto Label_00D0; case '.': if (!flag2) { goto Label_0119; } return(false); case '/': goto Label_00FE; case '%': goto Label_00A9; } } return(false); Label_00A9: if (++index == end) { return(false); } if (name[index] != ']') { if (name[index] != '/') { goto Label_00A9; } goto Label_00FE; } Label_00D0: start = index; index = end; goto Label_013F; Label_00F9: flag4 = true; goto Label_013D; Label_00FE: if (validateStrictAddress) { return(false); } if ((num == 0) || flag3) { return(false); } flag3 = true; flag4 = true; goto Label_013D; Label_0119: index = end; if (!IPv4AddressHelper.IsValid(name, num3, ref index, true, false)) { return(false); } num++; flag2 = true; index--; Label_013D: num2 = 0; Label_013F: index++; } if (!flag3 || ((num2 >= 1) && (num2 <= 2))) { int num5 = 8 + (flag3 ? 1 : 0); if ((flag4 || (num2 > 4)) || !(flag ? (num < num5) : (num == num5))) { return(false); } if (index == (end + 1)) { end = start + 1; return(true); } } return(false); }
internal static unsafe bool Parse(string address, ushort *numbers, int start, ref string scopeId) { int num = 0; int num2 = 0; int num3 = -1; bool flag = true; int num4 = 0; if (address[start] == '[') { start++; } int num5 = start; while ((num5 < address.Length) && (address[num5] != ']')) { switch (address[num5]) { case '%': { if (flag) { numbers[num2++] = (ushort)num; flag = false; } start = num5; num5++; while ((address[num5] != ']') && (address[num5] != '/')) { num5++; } scopeId = address.Substring(start, num5 - start); while (address[num5] != ']') { num5++; } continue; } case '/': { if (flag) { numbers[num2++] = (ushort)num; flag = false; } num5++; while (address[num5] != ']') { num4 = (num4 * 10) + (address[num5] - '0'); num5++; } continue; } case ':': { numbers[num2++] = (ushort)num; num = 0; num5++; if (address[num5] == ':') { num3 = num2; num5++; } else if ((num3 < 0) && (num2 < 6)) { continue; } for (int i = num5; (((address[i] != ']') && (address[i] != ':')) && ((address[i] != '%') && (address[i] != '/'))) && (i < (num5 + 4)); i++) { if (address[i] == '.') { while (((address[i] != ']') && (address[i] != '/')) && (address[i] != '%')) { i++; } num = IPv4AddressHelper.ParseHostNumber(address, num5, i); numbers[num2++] = (ushort)(num >> 0x10); numbers[num2++] = (ushort)num; num5 = i; num = 0; flag = false; break; } } continue; } } num = (num * 0x10) + Uri.FromHex(address[num5++]); } if (flag) { numbers[num2++] = (ushort)num; } if (num3 > 0) { int num7 = 7; int index = num2 - 1; for (int j = num2 - num3; j > 0; j--) { numbers[num7--] = numbers[index]; numbers[index--] = 0; } } if ((((numbers[0] != 0) || (numbers[1] != 0)) || ((numbers[2] != 0) || (numbers[3] != 0))) || (numbers[4] != 0)) { return(false); } if (((numbers[5] != 0) || (numbers[6] != 0)) || (numbers[7] != 1)) { if ((numbers[6] != 0x7f00) || (numbers[7] != 1)) { return(false); } if (numbers[5] != 0) { return(numbers[5] == 0xffff); } } return(true); }
public override ValidationResult Validate(object value, CultureInfo cultureInfo) { var isValid = true; if (value == null) { return(new ValidationResult(false, Resources.Localization.Strings.EnterValidIPScanRange)); } foreach (var ipHostOrRange in ((string)value).Replace(" ", "").Split(';')) { // like 192.168.0.1 if (Regex.IsMatch(ipHostOrRange, RegexHelper.IPv4AddressRegex)) { continue; } // like 192.168.0.0/24 if (Regex.IsMatch(ipHostOrRange, RegexHelper.IPv4AddressCidrRegex)) { continue; } // like 192.168.0.0/255.255.255.0 if (Regex.IsMatch(ipHostOrRange, RegexHelper.IPv4AddressSubnetmaskRegex)) { continue; } // like 192.168.0.0 - 192.168.0.100 if (Regex.IsMatch(ipHostOrRange, RegexHelper.IPv4AddressRangeRegex)) { var range = ipHostOrRange.Split('-'); if (IPv4AddressHelper.ConvertToInt32(IPAddress.Parse(range[0])) >= IPv4AddressHelper.ConvertToInt32(IPAddress.Parse(range[1]))) { isValid = false; } continue; } // like 192.168.[50-100].1 if (Regex.IsMatch(ipHostOrRange, RegexHelper.IPv4AddressSpecialRangeRegex)) { var octets = ipHostOrRange.Split('.'); foreach (var octet in octets) { // Match [50-100] if (!Regex.IsMatch(octet, RegexHelper.SpecialRangeRegex)) { continue; } foreach (var numberOrRange in octet.Substring(1, octet.Length - 2).Split(',')) { if (!numberOrRange.Contains("-")) { continue; } // 50-100 --> {50, 100} var rangeNumber = numberOrRange.Split('-'); if (int.Parse(rangeNumber[0]) > int.Parse(rangeNumber[1])) { isValid = false; } } } continue; } // like server-01.example.com if (Regex.IsMatch(ipHostOrRange, RegexHelper.HostnameRegex)) { continue; } // like server-01.example.com/24 if (Regex.IsMatch(ipHostOrRange, RegexHelper.HostnameCidrRegex)) { continue; } // like server-01.example.com/255.255.255.0 if (Regex.IsMatch(ipHostOrRange, RegexHelper.HostnameSubnetmaskRegex)) { continue; } isValid = false; } return(isValid ? ValidationResult.ValidResult : new ValidationResult(false, Resources.Localization.Strings.EnterValidIPScanRange)); }
// // IsValidStrict // // Determine whether a name is a valid IPv6 address. Rules are: // // * 8 groups of 16-bit hex numbers, separated by ':' // * a *single* run of zeros can be compressed using the symbol '::' // * an optional string of a ScopeID delimited by '%' // * the last 32 bits in an address can be represented as an IPv4 address // // Difference between IsValid() and IsValidStrict() is that IsValid() expects part of the string to // be ipv6 address where as IsValidStrict() expects strict ipv6 address. // // Inputs: // <argument> name // IPv6 address in string format // // Outputs: // Nothing // // Assumes: // the correct name is terminated by ']' character // // Returns: // true if <name> is IPv6 address, else false // // Throws: // Nothing // // Remarks: MUST NOT be used unless all input indexes are verified and trusted. // start must be next to '[' position, or error is reported internal unsafe static bool IsValidStrict(char *name, int start, ref int end) { int sequenceCount = 0; int sequenceLength = 0; bool haveCompressor = false; bool haveIPv4Address = false; bool expectingNumber = true; int lastSequence = 1; bool needsClosingBracket = false; if (start < end && name[start] == '[') { start++; needsClosingBracket = true; } int i; for (i = start; i < end; ++i) { if (Uri.IsHexDigit(name[i])) { ++sequenceLength; expectingNumber = false; } else { if (sequenceLength > 4) { return(false); } if (sequenceLength != 0) { ++sequenceCount; lastSequence = i - sequenceLength; sequenceLength = 0; } switch (name[i]) { case '%': while (i + 1 < end) { i++; if (name[i] == ']') { goto case ']'; } else if (name[i] == '/') { goto case '/'; } else if (name[i] < '0' || name[i] > '9') { // scope ID must only contain digits return(false); } } break; case ']': if (!needsClosingBracket) { return(false); } needsClosingBracket = false; // If there's more after the closing bracket, it must be a port. // We don't use the port, but we still validate it. if (i + 1 < end && name[i + 1] != ':') { return(false); } // If there is a port, it must either be a hexadecimal or decimal number. if (i + 3 < end && name[i + 2] == '0' && name[i + 3] == 'x') { i += 4; for (; i < end; i++) { if (!Uri.IsHexDigit(name[i])) { return(false); } } } else { i += 2; for (; i < end; i++) { if (name[i] < '0' || name[i] > '9') { return(false); } } } continue; case ':': if ((i > 0) && (name[i - 1] == ':')) { if (haveCompressor) { // can only have one per IPv6 address return(false); } haveCompressor = true; expectingNumber = false; } else { expectingNumber = true; } break; case '/': return(false); case '.': if (haveIPv4Address) { return(false); } i = end; if (!IPv4AddressHelper.IsValid(name, lastSequence, ref i, true, false, false)) { return(false); } // ipv4 address takes 2 slots in ipv6 address, one was just counted meeting the '.' ++sequenceCount; lastSequence = i - sequenceLength; sequenceLength = 0; haveIPv4Address = true; --i; // it will be incremented back on the next loop break; default: return(false); } sequenceLength = 0; } } if (sequenceLength != 0) { if (sequenceLength > 4) { return(false); } ++sequenceCount; } // these sequence counts are -1 because it is implied in end-of-sequence const int ExpectedSequenceCount = 8; return (!expectingNumber && (haveCompressor ? (sequenceCount < ExpectedSequenceCount) : (sequenceCount == ExpectedSequenceCount)) && !needsClosingBracket); }