public Server(string data) { data = data.Trim().Replace(" ", ""); string[] arguments = Regex.Split(data, ":"); if (arguments.Length != 2) { throw new ArgumentException("Wrong hostname"); } int port; if (!Int32.TryParse(arguments[1], out port) || port < 1 || port > 65535) { throw new ArgumentException("Wrong port"); } Port = port; Hostname = arguments[0]; UriHostNameType hostnameType = Uri.CheckHostName(Hostname); if (hostnameType == UriHostNameType.Unknown) // jeśli podana wartość nie jest nazwą domenową albo poprawnym adresem IP { throw new ArgumentException("Wrong hostname"); } else if (hostnameType == UriHostNameType.IPv4 || hostnameType == UriHostNameType.IPv6) { string IPv4Regex = "^([01]?[0-9]?[0-9]|2[0-4][0-9]|25[0-5])\\.([01]?[0-9]?[0-9]|2[0-4][0-9]|25[0-5])\\.([01]?[0-9]?[0-9]|2[0-4][0-9]|25[0-5])\\.([01]?[0-9]?[0-9]|2[0-4][0-9]|25[0-5])$"; string IPv6Regex = "^((?:[0-9A-Fa-f]{1,4}))((?::[0-9A-Fa-f]{1,4}))*::((?:[0-9A-Fa-f]{1,4}))((?::[0-9A-Fa-f]{1,4}))*|((?:[0-9A-Fa-f]{1,4}))((?::[0-9A-Fa-f]{1,4})){7}$"; if (!Regex.IsMatch(Hostname, IPv4Regex) && !Regex.IsMatch(Hostname, IPv6Regex)) { throw new ArgumentException("Wrong hostname"); } } }
/// <summary> /// Method to return IPAddress of reomote address for HttpRequest /// </summary> /// <param name="request">HttpRequest</param> /// <returns>IPAddress</returns> /// <method>GetRemoteAddress(this IPAddress ipAddress)</method> public static IPAddress GetRemoteAddress(this HttpRequest request) { IPAddress ipAddress = request.HttpContext.Connection.RemoteIpAddress; KeyValuePair <string, StringValues> xForwardedForHeader = request.HttpContext.Request.Headers .Where(x => x.Key.ToLower() == "x-forwarded-for") .FirstOrDefault(); if (!string.IsNullOrEmpty(xForwardedForHeader.Key)) { if (!string.IsNullOrEmpty(xForwardedForHeader.Value)) { UriHostNameType uriType = Uri.CheckHostName(xForwardedForHeader.Value); switch (uriType) { case UriHostNameType.IPv4: // strip any port from xForwardedForHeader IP Address string[] hostParts = xForwardedForHeader.Value.ToString().Split(':'); ipAddress = IPAddress.Parse(hostParts[0]); break; case UriHostNameType.IPv6: ipAddress = IPAddress.Parse(xForwardedForHeader.Value); break; } } } return(ipAddress); }
/// <summary> /// The get ip. /// </summary> /// <param name="domain"> /// The domain. /// </param> /// <returns> /// The get ip. /// </returns> public string GetIp(string domain) { try { UriHostNameType result = Uri.CheckHostName(domain); if (result == UriHostNameType.Unknown || result == UriHostNameType.Basic) { MessageBox.Show("Invalid hostname!"); return(string.Empty); } if (result == UriHostNameType.IPv4) { return(domain); } return(Dns.GetHostAddresses(domain)[0].ToString()); } catch (Exception) { MessageBox.Show("Invalid hostname!"); return(string.Empty); } }
/// <summary> /// Determine si es una dirección IP4, IP6 legal /// <para>eg: Assert.IsTrue(CheckHelper.IsIp46Address("192.168.1.1:8060"));</para> /// <para> Assert.IsTrue(CheckHelper.IsIp46Address("[2001:0DB8:02de::0e13]:9010"));</para> /// </summary> /// <param name="data">Cadena para ser juzgado</param> /// <returns>Si es legal, volverá a la parte del host. Si no es legal, volverá nulo.</returns> public static bool IsIp46Address(string data) { bool _result = false; if (!string.IsNullOrEmpty(data)) { UriHostNameType _hostType = Uri.CheckHostName(data); if (_hostType == UriHostNameType.Unknown) // Por ejemplo, "192.168.1.1:8060" o [2001: 0DB8: 02de :: 0e13]: 9010 { Uri _url; if (Uri.TryCreate(string.Format("http://{0}", data), UriKind.Absolute, out _url)) { _result = true; } } else if (_hostType == UriHostNameType.IPv4 || _hostType == UriHostNameType.IPv6) { _result = true; } } return(_result); }
private static IPEndPoint ResolveIPEndPoint(string serverIp, string serverPort) { UriHostNameType hostType = Uri.CheckHostName(serverIp); IPAddress address; switch (hostType) { case UriHostNameType.IPv4: case UriHostNameType.IPv6: IPAddress.TryParse(serverIp, out address); break; case UriHostNameType.Dns: address = ResolveHostName(serverIp, serverPort); break; default: return(null); } if (address == null) { return(null); } return(new IPEndPoint(address, int.Parse(serverPort))); }
/// <summary> /// Parses relative Uri into variables. /// </summary> /// <param name="uri">A Uri.</param> /// <exception cref="System.ArgumentNullException"> /// The <paramref name="uri"/> is null. /// </exception> /// <exception cref="System.Exception"> /// See constructor description. /// </exception> protected void ValidateRelativePath(string uri) { // Check for null if (uri == null || uri.Length == 0) { throw new ArgumentNullException(); } // Check for "//" if (uri[1] == '/') { throw new ArgumentException(); } // Check for alphnumeric and special characters for (int i = 1; i < uri.Length; ++i) { if (!IsAlphaNumeric(uri[i]) && ("()+,-.:=@;$_!*'").IndexOf(uri[i]) == -1) { throw new ArgumentException(); } } m_AbsolutePath = uri.Substring(1); m_host = ""; m_isAbsoluteUri = false; m_isUnc = false; m_hostNameType = UriHostNameType.Unknown; m_port = UnknownPort; }
private void ProcessSelection(TcpChannelListener channelListener, IPAddress ipAddressAny, UriHostNameType ipHostNameType, ref ExclusiveTcpTransportManager transportManager, IList<TransportManager> result) { if (transportManager == null) { transportManager = new ExclusiveTcpTransportManager(this, channelListener, ipAddressAny, ipHostNameType); } result.Add(transportManager); }
/// <summary> /// Returns true if the supplied value is a properly formatted IP address /// </summary> /// <param name="configValue">The value to check</param> /// <returns>True if the input is a properly formatted IP address, else false</returns> /// <remarks>This will not check to see if the address is reachable, only that it is formatted properly. This method will not throw exceptions.</remarks> protected internal static bool IsValidIpAddress(object configValue) { if (configValue != null) { UriHostNameType uriHostNameType = Uri.CheckHostName(configValue.ToString().Trim()); return(uriHostNameType == UriHostNameType.IPv4); } return(false); }
public ParsedUri(string _scheme, string _host, UriHostNameType _hostNameType, int _port, string _absolutePath, string _absoluteUri) { Scheme = _scheme; Host = _host; HostNameType = _hostNameType; Port = _port; AbsolutePath = _absolutePath; AbsoluteUri = _absoluteUri; }
protected void ValidateComputerName(string[] computerNames) { foreach (string str in computerNames) { UriHostNameType type = Uri.CheckHostName(str); if (((type != UriHostNameType.Dns) && (type != UriHostNameType.IPv4)) && (type != UriHostNameType.IPv6)) { base.ThrowTerminatingError(new ErrorRecord(new ArgumentException(PSRemotingErrorInvariants.FormatResourceString(RemotingErrorIdStrings.InvalidComputerName, new object[0])), "PSSessionInvalidComputerName", ErrorCategory.InvalidArgument, computerNames)); } } }
public static bool CheckIsValid(string url, UriHostNameType type) { Uri uri; var result = Uri.TryCreate(url, UriKind.Absolute, out uri); if (!result || uri.HostNameType != type || !uri.IsAbsoluteUri) { return(false); } return(true); }
private static void AssertHostNameIsValid(string hostName) { Ensure.NotEmpty(hostName, nameof(hostName)); UriHostNameType hostNameType = Uri.CheckHostName(hostName); if (hostNameType != UriHostNameType.Dns && hostNameType != UriHostNameType.IPv4) { throw new ArgumentException($"Invalid argument {nameof(hostName)} value: {hostName}"); } }
private static bool CheckHostName(JsonElement element, UriHostNameType type) { if (element.ValueKind != JsonValueKind.String) { return(false); } var actualType = System.Uri.CheckHostName(element.GetString()); return(actualType == type); }
/**********************************************************************************************//** * \fn public static bool CheckByPing(string apiBaseAddress, int timeOut = 2000) * * \brief Check by ping * * \author Delmiro Paes * * \exception PingException Thrown when a Ping error condition occurs. * * \param apiBaseAddress The API base address. * \param timeOut (Optional) The time out. * * \returns True if it succeeds, false if it fails. **************************************************************************************************/ public static bool CheckByPing(string apiBaseAddress, int timeOut = 2000) { bool pingResult = false; Ping pinger = null; if (string.IsNullOrWhiteSpace(apiBaseAddress)) { return(false); } UriHostNameType uriHostNameType = Uri.CheckHostName(apiBaseAddress); //UriHostNameType.Dns // type: http://localhost:9000/v1/xyz... if (uriHostNameType == UriHostNameType.Unknown) { //trying get it as URI. Uri uri = new Uri(apiBaseAddress); apiBaseAddress = new Uri(apiBaseAddress).Host; uriHostNameType = Uri.CheckHostName(apiBaseAddress); if (uriHostNameType == UriHostNameType.Dns) { IPAddress[] ipAddress = Dns.GetHostAddresses(apiBaseAddress); apiBaseAddress = ipAddress[0].ToString(); } } try { if (timeOut < 1) { throw new PingException("Timeout do ping deve ser superior a 0 ms."); } pinger = new Ping(); PingReply reply = pinger.Send(apiBaseAddress, timeOut); pingResult = reply.Status == IPStatus.Success; } catch (PingException) { pingResult = false; } finally { if (pinger != null) { pinger.Dispose(); } } return(pingResult); }
public void DomainLabelLength() { UriHostNameType type = Uri.CheckHostName("3.141592653589793238462643383279502884197169399375105820974944592.com"); Assert.AreEqual(UriHostNameType.Dns, type, "DomainLabelLength#1"); type = Uri.CheckHostName("3141592653589793238462643383279502884197169399375105820974944592.com"); Assert.AreEqual(UriHostNameType.Unknown, type, "DomainLabelLength#2"); type = Uri.CheckHostName("3.1415926535897932384626433832795028841971693993751058209749445923.com"); Assert.AreEqual(UriHostNameType.Unknown, type, "DomainLabelLength#2"); type = Uri.CheckHostName("3.141592653589793238462643383279502884197169399375105820974944592._om"); Assert.AreEqual(UriHostNameType.Unknown, type, "DomainLabelLength#3"); }
internal Socket GetListenSocket(UriHostNameType ipHostNameType) { if (ipHostNameType == UriHostNameType.IPv4) { Socket socket = this.ipv4ListenSocket; this.ipv4ListenSocket = null; return(socket); } Socket socket2 = this.ipv6ListenSocket; this.ipv6ListenSocket = null; return(socket2); }
public OSHTTPURI(string uri, bool withDNSResolve = false) { Host = string.Empty; Port = -1; m_URI = string.Empty; Path = string.Empty; HostType = UriHostNameType.Unknown; IP = null; if (string.IsNullOrEmpty(uri)) { return; } try { Uri m_checkuri = new Uri(uri); if (m_checkuri.Scheme != Uri.UriSchemeHttp && m_checkuri.Scheme != Uri.UriSchemeHttps) { return; } Host = m_checkuri.DnsSafeHost.ToLowerInvariant(); HostType = m_checkuri.HostNameType; Port = m_checkuri.Port; Path = m_checkuri.AbsolutePath; if (Path[Path.Length - 1] == '/') { Path = Path.Substring(0, Path.Length - 1); } m_URI = m_checkuri.Scheme + "://" + Host + ":" + Port + Path; if (withDNSResolve) { IPAddress ip = Util.GetHostFromDNS(Host); if (ip != null) { IP = ip; } } } catch { HostType = UriHostNameType.Unknown; IP = null; } }
private static void ValidateUri( string scheme, string host, UriHostNameType expectedHostType, string expectedHost, string expectedDnsSafeHost, string expectedIdnHost) { Assert.True(Uri.TryCreate(scheme + "://" + host, UriKind.Absolute, out Uri uri)); Assert.Equal(expectedHost, uri.Host); Assert.Equal(expectedDnsSafeHost, uri.DnsSafeHost); Assert.Equal(expectedHostType, uri.HostNameType); Assert.Equal(expectedHostType, Uri.CheckHostName(host)); Assert.Equal(expectedIdnHost, uri.IdnHost); }
/// <summary> /// Starts listening at the specified port. /// </summary> public void Start() { Startup.Listener = this; m_hostBuilder = new WebHostBuilder(); HttpsConnectionAdapterOptions httpsOptions = new HttpsConnectionAdapterOptions(); httpsOptions.CheckCertificateRevocation = false; httpsOptions.ClientCertificateMode = ClientCertificateMode.NoCertificate; httpsOptions.ServerCertificate = m_serverCert; #if NET462 // note: although security tools recommend 'None' here, // it only works on .NET 4.6.2 if Tls12 is used #pragma warning disable CA5398 // Avoid hardcoded SslProtocols values httpsOptions.SslProtocols = SslProtocols.Tls12; #pragma warning restore CA5398 // Avoid hardcoded SslProtocols values #else httpsOptions.SslProtocols = SslProtocols.None; #endif bool bindToSpecifiedAddress = true; UriHostNameType hostType = Uri.CheckHostName(m_uri.Host); if (hostType == UriHostNameType.Dns || hostType == UriHostNameType.Unknown || hostType == UriHostNameType.Basic) { bindToSpecifiedAddress = false; } if (bindToSpecifiedAddress) { IPAddress ipAddress = IPAddress.Parse(m_uri.Host); m_hostBuilder.UseKestrel(options => { options.Listen(ipAddress, m_uri.Port, listenOptions => { listenOptions.UseHttps(httpsOptions); }); }); } else { m_hostBuilder.UseKestrel(options => { options.ListenAnyIP(m_uri.Port, listenOptions => { listenOptions.UseHttps(httpsOptions); }); }); } m_hostBuilder.UseContentRoot(Directory.GetCurrentDirectory()); m_hostBuilder.UseStartup <Startup>(); m_host = m_hostBuilder.Start(Utils.ReplaceLocalhost(m_uri.ToString())); }
private void ValidateAddress(object sender, CancelEventArgs e) { MetroTextBox Box = (MetroTextBox)sender; // Validate Hostname or IP (Yes this works for both!) UriHostNameType Type = Uri.CheckHostName(Box.Text); if (Type == UriHostNameType.Unknown) { HasInputErrors = true; metroToolTip1.SetToolTip(Box, " Invalid hostname or IPAddress provided. "); Box.WithError = true; return; } Box.WithError = false; }
private void btnTraceroute_Click(object sender, EventArgs e) { // Validate the form UriHostNameType hostType = Uri.CheckHostName(tbTarget.Text); if (hostType == UriHostNameType.Unknown) { MessageBox.Show("Please enter a valid target hostname."); return; } int ttl; if (!int.TryParse(tbTTL.Text, out ttl)) { MessageBox.Show("Please enter a valid TTL (Time to Live) value."); return; } int hops; if (!int.TryParse(tbMaxHops.Text, out hops)) { MessageBox.Show("Please enter a valid max hop count."); return; } // Start the worker if (workerRunning) { this.tracerouteWorker.CancelAsync(); this.btnTraceroute.Text = "Cancelling..."; this.btnTraceroute.Enabled = false; } else { hopEntries.Clear(); this.tbTarget.Enabled = this.tbTTL.Enabled = this.tbMaxHops.Enabled = false; var args = Tuple.Create <string, int, int>(tbTarget.Text, ttl, hops); this.tracerouteWorker.RunWorkerAsync(args); this.btnTraceroute.Text = "Cancel"; workerRunning = true; } }
private static ServiceNameCollection GetDefaultSpnList(System.ServiceModel.HostNameComparisonMode hostNameComparisonMode, Uri listenUri) { Dictionary <string, string> list = new Dictionary <string, string>(); string hostName = null; string dnsSafeHost = listenUri.DnsSafeHost; switch (hostNameComparisonMode) { case System.ServiceModel.HostNameComparisonMode.StrongWildcard: case System.ServiceModel.HostNameComparisonMode.WeakWildcard: hostName = Dns.GetHostEntry(string.Empty).HostName; AddSpn(list, string.Format(CultureInfo.InvariantCulture, "HOST/{0}", new object[] { hostName })); AddSpn(list, string.Format(CultureInfo.InvariantCulture, "HTTP/{0}", new object[] { hostName })); break; case System.ServiceModel.HostNameComparisonMode.Exact: { UriHostNameType hostNameType = listenUri.HostNameType; if ((hostNameType != UriHostNameType.IPv4) && (hostNameType != UriHostNameType.IPv6)) { if (listenUri.DnsSafeHost.Contains(".")) { AddSpn(list, string.Format(CultureInfo.InvariantCulture, "HOST/{0}", new object[] { dnsSafeHost })); AddSpn(list, string.Format(CultureInfo.InvariantCulture, "HTTP/{0}", new object[] { dnsSafeHost })); } else { hostName = Dns.GetHostEntry(string.Empty).HostName; AddSpn(list, string.Format(CultureInfo.InvariantCulture, "HOST/{0}", new object[] { dnsSafeHost })); AddSpn(list, string.Format(CultureInfo.InvariantCulture, "HTTP/{0}", new object[] { dnsSafeHost })); AddSpn(list, string.Format(CultureInfo.InvariantCulture, "HOST/{0}", new object[] { hostName })); AddSpn(list, string.Format(CultureInfo.InvariantCulture, "HTTP/{0}", new object[] { hostName })); } break; } hostName = Dns.GetHostEntry(string.Empty).HostName; AddSpn(list, string.Format(CultureInfo.InvariantCulture, "HOST/{0}", new object[] { hostName })); AddSpn(list, string.Format(CultureInfo.InvariantCulture, "HTTP/{0}", new object[] { hostName })); break; } } AddSpn(list, string.Format(CultureInfo.InvariantCulture, "HOST/{0}", new object[] { "localhost" })); AddSpn(list, string.Format(CultureInfo.InvariantCulture, "HTTP/{0}", new object[] { "localhost" })); return(new ServiceNameCollection(list.Values)); }
public override string OnSave(Settings settings) { if (this.inputText.text == String.Empty) { return(""); } UriHostNameType host = Uri.CheckHostName(this.inputText.text); if (host == UriHostNameType.Unknown) { return("Inserted host isn't valid"); } if (host == UriHostNameType.IPv6) { return("IPv6 address aren't supported"); } return(""); }
private static bool IsValidHostname(string hostname) { if (string.IsNullOrEmpty(hostname)) { return(false); } else { UriHostNameType hostnameType = Uri.CheckHostName(hostname); if (hostnameType == UriHostNameType.Dns) { return(true); } else { return(false); } } }
public ExclusiveTcpTransportManager(ExclusiveTcpTransportManagerRegistration registration, TcpChannelListener channelListener, System.Net.IPAddress ipAddressAny, UriHostNameType ipHostNameType) { base.ApplyListenerSettings(channelListener); this.listenSocket = channelListener.GetListenSocket(ipHostNameType); if (this.listenSocket != null) { this.ipAddress = ((IPEndPoint) this.listenSocket.LocalEndPoint).Address; } else if (channelListener.Uri.HostNameType == ipHostNameType) { this.ipAddress = System.Net.IPAddress.Parse(channelListener.Uri.DnsSafeHost); } else { this.ipAddress = ipAddressAny; } this.listenBacklog = channelListener.ListenBacklog; this.registration = registration; }
private void CheckParsed() { if ((this.host == null || this.host == "") && (this.scheme == "file" || this.scheme == null)) { this.scheme = UriSchemeFile; this.delim = "://"; } else { this.hostNameType = CheckHostName(this.host); if (hostNameType == UriHostNameType.Unknown) { throw new UriFormatException(S._("Arg_UriHostName")); } } if (!CheckSchemeName(this.scheme)) { throw new UriFormatException(S._("Arg_UriScheme")); } if (portString != null) { try { int value = Int32.Parse(portString); port = value; } catch (FormatException) { this.port = -1; } catch (OverflowException) { throw new UriFormatException(S._("Arg_UriPort")); } } else { this.port = DefaultPortForScheme(this.scheme); } }
// Segments cannot be validated here... public void AssertUri(string relsrc, Uri uri, string toString, string absoluteUri, string scheme, string host, string localPath, string query, int port, bool isFile, bool isUnc, bool isLoopback, bool userEscaped, UriHostNameType hostNameType, string absolutePath, string pathAndQuery, string authority, string fragment, string userInfo) { Assert.AreEqual(absoluteUri, uri.AbsoluteUri, relsrc + " AbsoluteUri"); Assert.AreEqual(scheme, uri.Scheme, relsrc + " Scheme"); Assert.AreEqual(host, uri.Host, relsrc + " Host"); Assert.AreEqual(port, uri.Port, relsrc + " Port"); // Windows UNC path is not automatically testable on *nix environment, if (relsrc.StartsWith("\\\\") && Path.DirectorySeparatorChar == '\\') { Assert.AreEqual(localPath, uri.LocalPath, relsrc + " LocalPath"); } Assert.AreEqual(query, uri.Query, relsrc + " Query"); Assert.AreEqual(fragment, uri.Fragment, relsrc + " Fragment"); Assert.AreEqual(isFile, uri.IsFile, relsrc + " IsFile"); Assert.AreEqual(isUnc, uri.IsUnc, relsrc + " IsUnc"); Assert.AreEqual(isLoopback, uri.IsLoopback, relsrc + " IsLoopback"); Assert.AreEqual(authority, uri.Authority, relsrc + " Authority"); Assert.AreEqual(userEscaped, uri.UserEscaped, relsrc + " UserEscaped"); Assert.AreEqual(userInfo, uri.UserInfo, relsrc + " UserInfo"); Assert.AreEqual(hostNameType, uri.HostNameType, relsrc + " HostNameType"); Assert.AreEqual(absolutePath, uri.AbsolutePath, relsrc + " AbsolutePath"); Assert.AreEqual(pathAndQuery, uri.PathAndQuery, relsrc + " PathAndQuery"); Assert.AreEqual(toString, uri.ToString(), relsrc + " ToString()"); }
private void CheckIp(string domain) { try { int port = 1; if (domain.Contains(":")) { port = Convert.ToInt32(domain.Split(new char[] { ':' }, 2)[1]); if (port > 65536 || port < 1) { port = 26000; } UriHostNameType result = Uri.CheckHostName(domain.Split(new char[] { ':' }, 2)[0]); if (result == UriHostNameType.Unknown || result == UriHostNameType.Basic) { textBox.Text = ""; } else { textBox.Text = domain.Split(new char[] { ':' }, 2)[0] + ":" + port; } } else { UriHostNameType result2 = Uri.CheckHostName(domain); if (result2 == UriHostNameType.Unknown || result2 == UriHostNameType.Basic) { textBox.Text = ""; } } } catch (Exception) { textBox.Text = ""; } }
// Segments cannot be validated here... public void AssertUri (string relsrc, Uri uri, string toString, string absoluteUri, string scheme, string host, string localPath, string query, int port, bool isFile, bool isUnc, bool isLoopback, bool userEscaped, UriHostNameType hostNameType, string absolutePath, string pathAndQuery, string authority, string fragment, string userInfo) { AssertEquals (relsrc + " AbsoluteUri", absoluteUri, uri.AbsoluteUri); AssertEquals (relsrc + " Scheme", scheme, uri.Scheme); AssertEquals (relsrc + " Host", host, uri.Host); AssertEquals (relsrc + " Port", port, uri.Port); // Windows UNC path is not automatically testable on *nix environment, if (relsrc.StartsWith ("\\\\") && Path.DirectorySeparatorChar == '\\') AssertEquals (relsrc + " LocalPath", localPath, uri.LocalPath); AssertEquals (relsrc + " Query", query, uri.Query); AssertEquals (relsrc + " Fragment", fragment, uri.Fragment); AssertEquals (relsrc + " IsFile", isFile, uri.IsFile); AssertEquals (relsrc + " IsUnc", isUnc, uri.IsUnc); AssertEquals (relsrc + " IsLoopback", isLoopback, uri.IsLoopback); AssertEquals (relsrc + " Authority", authority, uri.Authority); AssertEquals (relsrc + " UserEscaped", userEscaped, uri.UserEscaped); AssertEquals (relsrc + " UserInfo", userInfo, uri.UserInfo); AssertEquals (relsrc + " HostNameType", hostNameType, uri.HostNameType); AssertEquals (relsrc + " AbsolutePath", absolutePath, uri.AbsolutePath); AssertEquals (relsrc + " PathAndQuery", pathAndQuery, uri.PathAndQuery); AssertEquals (relsrc + " ToString()", toString, uri.ToString ()); }
public SmartUri(IPEndPoint endpoint) { if (endpoint == null) { throw new ArgumentNullException("endpoint"); } this.HostNameType = SmartUri.GetHostNameType(endpoint.Address); this.Host = endpoint.Address.ToString(); string str; if (this.HostNameType != UriHostNameType.IPv6) { str = this.Host; } else { str = this.Host.Trim('[', ']'); } this.DnsFriendlyHost = str; this.Port = endpoint.Port; this.IPEndPoint = endpoint; }
public System.Net.IPAddress GetIPAddress(string targetHost, out UriHostNameType typeOfAddr) { typeOfAddr = UriHostNameType.Basic; System.Net.IPAddress targetIP = null; try { var hostNameType = Uri.CheckHostName(targetHost); typeOfAddr = hostNameType; switch (hostNameType) { case UriHostNameType.Dns: var iph = System.Net.Dns.GetHostEntry(targetHost); if (null != iph && null != iph.AddressList) { var firstIP = iph.AddressList.First(); if (null != firstIP && !String.IsNullOrWhiteSpace(firstIP.ToString())) { targetIP = firstIP; typeOfAddr = Uri.CheckHostName(targetIP.ToString()); } } break; case UriHostNameType.IPv6: case UriHostNameType.IPv4: targetIP = System.Net.IPAddress.Parse(targetHost); break; default: return(null); } } catch (Exception ex) { ServerComms.LogError($@"Failed to resolve typeof Host: {ex.Message}"); return(null); } return(targetIP); }
public string MapUriHostNameType(UriHostNameType type) { switch (type) { case UriHostNameType.Unknown: return("Unknown"); case UriHostNameType.Basic: return("Basic"); case UriHostNameType.Dns: return("DNS"); case UriHostNameType.IPv4: return("IPv4"); case UriHostNameType.IPv6: return("IPv6"); default: throw new ArgumentOutOfRangeException("type"); } }
/// <summary> /// 判断是否是合法的IP4,IP6地址 /// <para>eg: Assert.IsTrue(CheckHelper.IsIp46Address("192.168.1.1:8060"));</para> /// <para> Assert.IsTrue(CheckHelper.IsIp46Address("[2001:0DB8:02de::0e13]:9010"));</para> /// </summary> /// <param name="data">需要判断的字符串</param> /// <returns>合法则返回host部分,若不合法则返回空</returns> public static bool IsIp46Address(string data) { bool result = false; if (!string.IsNullOrEmpty(data)) { UriHostNameType hostType = Uri.CheckHostName(data); if (hostType == UriHostNameType.Unknown) //譬如 "192.168.1.1:8060"或者[2001:0DB8:02de::0e13]:9010 { if (Uri.TryCreate(string.Format("http://{0}", data), UriKind.Absolute, out _)) { result = true; } } else if (hostType == UriHostNameType.IPv4 || hostType == UriHostNameType.IPv6) { result = true; } } return(result); }
public static bool IsSupportedHostNameType(UriHostNameType hostNameType) { return hostNameType == UriHostNameType.Dns || hostNameType == UriHostNameType.IPv4 || hostNameType == UriHostNameType.IPv6; }
/// <summary> /// Internal method parses a URI string into Uri variables /// </summary> /// <param name="uriString">A Uri.</param> /// <exception cref="System.ArgumentNullException"> /// The <paramref name="uriString"/> is null. /// </exception> /// <exception cref="System.Exception"> /// See constructor description. /// </exception> protected void ParseUriString(ref string uriString) { int startIndex = 0; int endIndex = 0; // Check for null or empty string. if (uriString == null || uriString.Length == 0) throw new ArgumentNullException(); // Check for presence of ':'. Colon always should be present in URI. if (uriString.IndexOf(':') == -1) { throw new ArgumentException(); } string uriStringLower = uriString.ToLower(); // If this is a urn parse and return if (uriStringLower.IndexOf("urn:", startIndex) == 0) { ValidateUrn(uriString); return; } // If the uri is a relative path parse and return if (uriString[0] == '/') { ValidateRelativePath(uriString); return; } // Validate Scheme endIndex = uriString.IndexOf(':'); m_scheme = uriString.Substring(0, endIndex); ; if (!IsAlpha(m_scheme[0])) throw new ArgumentException(); for (int i = 1; i < m_scheme.Length; ++i) if (!(IsAlphaNumeric(m_scheme[i]) || m_scheme[i] == '+' || m_scheme[i] == '-' || m_scheme[i] == '.')) throw new ArgumentException(); // Get past the colon startIndex = endIndex + 1; // If this is an http uri parse the host. IP host should start with // string schemeLower = m_scheme.ToLower(); if (schemeLower == "http" || schemeLower == "https") { if (uriString.Substring(startIndex).IndexOf("//") == 0) { // Set the host start index an determine if the host includes a port startIndex = startIndex + 2; if ((endIndex = uriString.IndexOf(':', startIndex)) != -1) { // If port is listed, parse to port sentinel m_host = uriString.Substring(startIndex, endIndex - startIndex); startIndex = startIndex + m_host.Length; // Look for the path sentinel endIndex = uriString.IndexOf('/', startIndex); // If there was no '/' at the end, we add it. For HTTP it means root page if address is http://www.microsoft.com if (endIndex == -1) { uriString += '/'; endIndex = uriString.IndexOf('/', startIndex); } ++startIndex; int portLength = endIndex - startIndex; m_port = Convert.ToInt32(uriString.Substring(startIndex, portLength)); startIndex += portLength; } else { if ((endIndex = uriString.IndexOf('/', startIndex)) == -1) { // If "/" was not found, means it is just host address like http://itgproxy.dns.microsoft.com // In this case we add add "/" and repeat the same operation as in prevo uriString += '/'; endIndex = uriString.IndexOf('/', startIndex); } m_host = uriString.Substring(startIndex, endIndex - startIndex); startIndex = startIndex + m_host.Length; // The control flow comes here only if schemeLower is http or https. // Thus we have only 2 cases. switch (schemeLower) { case "http": m_port = HttpDefaultPort; break; case "https": m_port = HttpsDefaultPort; break; } } m_isAbsoluteUri = true; } else throw new ArgumentException(); if (m_host[0] == '[') { m_hostNameType = UriHostNameType.IPv6; } else if (IsIPv4(m_host)) { m_hostNameType = UriHostNameType.IPv4; } else { m_hostNameType = UriHostNameType.Dns; } } // The last test is for a scheme and valid path else { if (m_scheme == null) { throw new ArgumentException(); } // Check that remaining part of Uri is valid ValidateUriPart(uriString, startIndex); m_hostNameType = UriHostNameType.Unknown; m_isAbsoluteUri = true; } // Set Uri properties m_AbsolutePath = uriString.Substring(startIndex, uriString.Length - startIndex); if (m_host != null) { string hostLower = m_host.ToLower(); if (hostLower == "localhost" || hostLower == "loopback") { m_Flags |= m_Flags | (int)Flags.LoopbackHost; } } m_isUnc = false; return; }
public void ValidateUri( string scheme, string host, UriHostNameType expectedHostType, string expectedHost, string expectedDnsSafeHost, string expectedIdnHost) { Uri uri; Assert.True(Uri.TryCreate(scheme + "://" + host, UriKind.Absolute, out uri)); Assert.Equal(expectedHost, uri.Host); Assert.Equal(expectedDnsSafeHost, uri.DnsSafeHost); Assert.Equal(expectedHostType, uri.HostNameType); Assert.Equal(expectedHostType, Uri.CheckHostName(host)); Assert.Equal(expectedIdnHost, uri.IdnHost); }
/// <summary> /// Parses relative Uri into variables. /// </summary> /// <param name="uri">A Uri.</param> /// <exception cref="System.ArgumentNullException"> /// The <paramref name="uri"/> is null. /// </exception> /// <exception cref="System.Exception"> /// See constructor description. /// </exception> protected void ValidateRelativePath(string uri) { // Check for null if (uri == null || uri.Length == 0) throw new ArgumentNullException(); // Check for "//" if (uri[1] == '/') throw new ArgumentException(); // Check for alphnumeric and special characters for (int i = 1; i < uri.Length; ++i) if (!IsAlphaNumeric(uri[i]) && ("()+,-.:=@;$_!*'").IndexOf(uri[i]) == -1) throw new ArgumentException(); m_AbsolutePath = uri.Substring(1); m_host = ""; m_isAbsoluteUri = false; m_isUnc = false; m_hostNameType = UriHostNameType.Unknown; m_port = UnknownPort; }
/// <summary> /// Parses urn string into Uri variables. /// Parsing is restricted to basic urn:NamespaceID, urn:uuid formats only. /// </summary> /// <param name="uri">A Uri.</param> /// <exception cref="System.ArgumentNullException"> /// The <paramref name="uri"/> is null. /// </exception> /// <exception cref="System.Exception"> /// See the constructor description. /// </exception> protected void ValidateUrn(string uri) { bool invalidUrn = false; // If this is a urn:uuid validate the uuid if (uri.ToLower().IndexOf("urn:uuid:", 0) == 0) { char[] tempUUID = uri.Substring(9).ToLower().ToCharArray(); int length = tempUUID.Length; int uuidSegmentCount = 0; int[] delimiterIndexes = { 8, 13, 18, 23 }; for (int i = 0; i < length; ++i) { // Make sure these are valid hex numbers numbers if (!IsHex(tempUUID[i]) && tempUUID[i] != '-') { invalidUrn = true; break; } else { // Check each segment length if (tempUUID[i] == '-') { if (uuidSegmentCount > 3) { invalidUrn = true; break; } if (i != delimiterIndexes[uuidSegmentCount]) { invalidUrn = true; break; } ++uuidSegmentCount; } } } m_AbsolutePath = uri.Substring(4); } // Else validate against RFC2141 else { string lowerUrn = uri.Substring(4).ToLower(); char[] tempUrn = lowerUrn.ToCharArray(); // Validate the NamespaceID (NID) int index = lowerUrn.IndexOf(':'); if (index == -1) throw new ArgumentException(); int i = 0; for (i = 0; i < index; ++i) { // Make sure these are valid hex numbers numbers if (!IsAlphaNumeric(tempUrn[i]) && tempUrn[i] != '-') { invalidUrn = true; break; } } // Validate the Namespace String tempUrn = lowerUrn.Substring(index + 1).ToCharArray(); int urnLength = tempUrn.Length; if (!invalidUrn && urnLength != 0) { string otherChars = "()+,-.:=@;$_!*'"; for (i = 0; i < urnLength; ++i) { if (!IsAlphaNumeric(tempUrn[i]) && !IsHex(tempUrn[i]) && tempUrn[i] != '%' && otherChars.IndexOf(tempUrn[i]) == -1) { invalidUrn = true; break; } } m_AbsolutePath = uri.Substring(4); } } if (invalidUrn) throw new ArgumentNullException(); // Set Uri properties m_host = ""; m_isAbsoluteUri = true; m_isUnc = false; m_hostNameType = UriHostNameType.Unknown; m_port = UnknownPort; m_scheme = "urn"; m_absoluteUri = uri; return; }
/// <summary> /// Internal method parses a URI string into Uri variables /// </summary> /// <param name="uriString">A Uri.</param> /// <exception cref="System.ArgumentNullException"> /// The <paramref name="uriString"/> is null. /// </exception> /// <exception cref="System.Exception"> /// See constructor description. /// </exception> protected void ParseUriString(string uriString) { int startIndex = 0; int endIndex = 0; // Check for null or empty string. if (uriString == null || uriString.Length == 0) { throw new ArgumentNullException(); } uriString = uriString.Trim(); // Check for presence of ':'. Colon always should be present in URI. if (uriString.IndexOf(':') == -1) { throw new ArgumentException(); } string uriStringLower = uriString.ToLower(); // If this is a urn parse and return if (uriStringLower.IndexOf("urn:", startIndex) == 0) { ValidateUrn(uriString); return; } // If the uri is a relative path parse and return if (uriString[0] == '/') { ValidateRelativePath(uriString); return; } // Validate Scheme endIndex = uriString.IndexOf(':'); m_scheme = uriString.Substring(0, endIndex); if (!IsAlpha(m_scheme[0])) { throw new ArgumentException(); } for (int i = 1; i < m_scheme.Length; ++i) { if (!(IsAlphaNumeric(m_scheme[i]) || m_scheme[i] == '+' || m_scheme[i] == '-' || m_scheme[i] == '.')) { throw new ArgumentException(); } } // Get past the colon startIndex = endIndex + 1; if (startIndex >= uriString.Length) { throw new ArgumentException(); } // Get host, port and absolute path bool bRooted = ParseSchemeSpecificPart(uriString, startIndex); if ((m_scheme == "file" || m_scheme == "mailto") && m_host.Length == 0) { m_hostNameType = UriHostNameType.Basic; } else if (m_host.Length == 0) { m_hostNameType = UriHostNameType.Unknown; } else if (m_host[0] == '[') { if (!IsIPv6(m_host)) { throw new ArgumentException(); } m_hostNameType = UriHostNameType.IPv6; } else if (IsIPv4(m_host)) { m_hostNameType = UriHostNameType.IPv4; } else { m_hostNameType = UriHostNameType.Dns; } if (m_host != null) { if (m_host == "localhost" || m_host == "loopback" || (m_scheme == "file" || m_scheme == "mailto") && m_host.Length == 0) { m_Flags |= m_Flags | (int)Flags.LoopbackHost; } } m_absoluteUri = m_scheme + ":" + (bRooted ? "//" : string.Empty) + m_host + ((DefaultPort(m_scheme) == m_port) ? string.Empty : ":" + m_port.ToString()) + (m_scheme == "file" && m_AbsolutePath.Length >= 2 && IsAlpha(m_AbsolutePath[0]) && m_AbsolutePath[1] == ':' ? "/" : string.Empty) + m_AbsolutePath; m_isAbsoluteUri = true; m_isUnc = m_scheme == "file" && m_host.Length > 0; }
public void CheckHostName(string name, UriHostNameType expected) { Assert.Equal(expected, Uri.CheckHostName(name)); }
private void CheckParsed() { if((this.host==null || this.host=="") && (this.scheme=="file" || this.scheme==null)) { this.scheme=UriSchemeFile; this.delim="://"; } else { this.hostNameType = CheckHostName(this.host); if(hostNameType==UriHostNameType.Unknown) { throw new UriFormatException(S._("Arg_UriHostName")); } } if(!CheckSchemeName(this.scheme)) { throw new UriFormatException(S._("Arg_UriScheme")); } if(portString!= null) { try { int value=Int32.Parse(portString); port = value; } catch(FormatException) { this.port = -1; } catch(OverflowException) { throw new UriFormatException (S._("Arg_UriPort")); } } else { this.port = DefaultPortForScheme(this.scheme); } }
public void Scheme_Authority_Basic(string uriString, string scheme, string userInfo, string host, UriHostNameType hostNameType, int port, bool isDefaultPort, bool isLoopback) { string idnHost = host; if (hostNameType == UriHostNameType.IPv6) { idnHost = host.Substring(1, host.Length - 2); } Scheme_Authority_IdnHost(uriString, scheme, userInfo, host, idnHost, idnHost, hostNameType, port, isDefaultPort, isLoopback); }
public void Scheme_Authority_IdnHost(string uriString, string scheme, string userInfo, string host, string idnHost, string dnsSafeHost, UriHostNameType hostNameType, int port, bool isDefaultPort, bool isLoopback) { string authority = host; if (!isDefaultPort) { authority += ":" + port.ToString(); } PerformAction(uriString, UriKind.Absolute, uri => { Assert.Equal(scheme, uri.Scheme); Assert.Equal(authority, uri.Authority); Assert.Equal(userInfo, uri.UserInfo); Assert.Equal(host, uri.Host); Assert.Equal(idnHost, uri.IdnHost); Assert.Equal(dnsSafeHost, uri.DnsSafeHost); Assert.Equal(hostNameType, uri.HostNameType); Assert.Equal(port, uri.Port); Assert.Equal(isDefaultPort, uri.IsDefaultPort); Assert.Equal(isLoopback, uri.IsLoopback); Assert.True(uri.IsAbsoluteUri); Assert.False(uri.UserEscaped); }); }