NetworkHelper
Provides various network helper extension methods.
Methods
public static void ApplyChromeAgent(HttpClient client)
NetworkHelper.ApplyChromeAgent(client)
Applies a Chrome user agent to the HttpClient.
- client
- The HttpClient instance.
public static bool CheckContainsUrl(string url)
result = NetworkHelper.CheckContainsUrl(url)
Checks if the URL contains any of the predefined URL parts.
- url
- The URL to check.
Returns: true if the URL contains one of the parts; otherwise, false.
public static string CheckUrl(string str, bool latin, bool screen, bool clear)
result = NetworkHelper.CheckUrl(str, latin, screen, clear)
Checks and cleans a URL by converting to Latin characters, screening, and clearing unsafe characters.
- str
- The URL string to check.
- latin
- if set to true converts characters to Latin.
- screen
- if set to true performs light screening.
- clear
- if set to true clears unsafe URL characters.
Returns: The processed URL.
public static string ClearUrl(string url)
result = NetworkHelper.ClearUrl(url)
Removes unsafe characters from the URL.
- url
- The URL to clear.
Returns: The cleared URL string.
public static ValueTask ConnectAsync(TcpClient client, EndPoint address, CancellationToken cancellationToken)
result = NetworkHelper.ConnectAsync(client, address, cancellationToken)
Connects the TcpClient to the specified endpoint.
- client
- The TcpClient instance.
- address
- The endpoint to connect to.
- cancellationToken
- CancellationToken
Returns: Task
public static HttpRequestException CreateHttpRequestException(HttpStatusCode code, string message)
result = NetworkHelper.CreateHttpRequestException(code, message)
Creates an HttpRequestException for the specified HTTP status code and message.
- code
- The HTTP status code.
- message
- The error message.
Returns: An instance of HttpRequestException.
public static string DecodeFromHtml(string text)
result = NetworkHelper.DecodeFromHtml(text)
Decodes the specified HTML-encoded text.
- text
- The text to decode.
Returns: The decoded string.
public static string DecodeUrl(string url)
result = NetworkHelper.DecodeUrl(url)
Decodes the specified URL.
- url
- The URL to decode.
Returns: The decoded URL string.
public static string EncodeToHtml(string text)
result = NetworkHelper.EncodeToHtml(text)
Encodes the specified text into its HTML-encoded representation.
- text
- The text to encode.
Returns: The HTML-encoded string.
public static string EncodeUrl(string url)
result = NetworkHelper.EncodeUrl(url)
Encodes a URL using UTF8 encoding.
- url
- The URL to encode.
Returns: The encoded URL string.
public static string EncodeUrlUpper(string url)
result = NetworkHelper.EncodeUrlUpper(url)
Encodes a URL ensuring uppercase encoding.
- url
- The URL to encode.
Returns: The URL encoded in uppercase.
public static IEnumerable<ValueTuple<string, string>> ExcludeEmpty(NameValueCollection col)
result = NetworkHelper.ExcludeEmpty(col)
Enumerates key-value pairs from the collection, excluding empty keys.
- col
- The name-value collection.
Returns: An enumerable of non-empty key-value pairs.
public static string Format<T>(T value, bool encode)
result = NetworkHelper.Format(value, encode)
Formats the value as a string with optional URL encoding.
- value
- The value to format.
- encode
- Whether to URL encode the result.
Returns: The formatted string.
public static TimeSpan GetDelay(RetryPolicyInfo policy, int attemptNumber)
result = NetworkHelper.GetDelay(policy, attemptNumber)
Calculates the delay for a retry based on the current attempt number.
- policy
- The retry policy information.
- attemptNumber
- The current attempt number.
Returns: A TimeSpan representing the delay.
public static string GetGravatarToken(string email)
result = NetworkHelper.GetGravatarToken(email)
Computes the Gravatar token for the specified email.
- The email address.
Returns: The computed Gravatar token.
public static string GetGravatarUrl(string token, int size)
result = NetworkHelper.GetGravatarUrl(token, size)
Constructs the Gravatar URL using the provided token and size.
- token
- The Gravatar token.
- size
- The size of the Gravatar image.
Returns: The full Gravatar image URL.
public static bool IsFileUriPath(string path)
result = NetworkHelper.IsFileUriPath(path)
Determines if the specified path is a file:// URI.
- path
- Path to check.
Returns: true if the path is a file:// URI; otherwise, false.
public static bool IsHostPortAddress(string address)
result = NetworkHelper.IsHostPortAddress(address)
Determines if the specified string is a host:port address (e.g., 127.0.0.1:5001, localhost:5001).
- address
- Address to check.
Returns: true if the string is a host:port address; otherwise, false.
public static bool IsImage(string fileName)
result = NetworkHelper.IsImage(fileName)
Determines whether the specified file name represents an image.
- fileName
- The file name to check.
Returns: true if the file is an image; otherwise, false.
public static bool IsImageVector(string fileName)
result = NetworkHelper.IsImageVector(fileName)
Determines whether the specified file name represents a vector image.
- fileName
- The file name to check.
Returns: true if the file is a vector image; otherwise, false.
public static bool IsInSubnet(IPAddress address, string subnetMask)
result = NetworkHelper.IsInSubnet(address, subnetMask)
Determines whether the specified IPv4 or IPv6 address is part of the given subnet.
- address
- The IP address to check.
- subnetMask
- The subnet mask in "IP/PrefixLength" format.
Returns: true if the address is in the subnet; otherwise, false.
public static bool IsInternal(IPAddress address)
result = NetworkHelper.IsInternal(address)
Determines whether the specified IPAddress is an internal (non-public) address: loopback, private (RFC 1918), link-local (incl. the 169.254.169.254 cloud-metadata endpoint), CGNAT (100.64.0.0/10), the 0.0.0.0/8 "this network" range, or the IPv6 unique-local / link-local ranges. IPv4-mapped IPv6 addresses are evaluated as their IPv4 form. Useful for SSRF deny-lists.
- address
- The IP address to check.
Returns: true if the address is internal/non-public; otherwise, false.
public static bool IsIPv4Multicast(IPAddress address)
result = NetworkHelper.IsIPv4Multicast(address)
Determines whether the specified IPAddress is an IPv4 multicast address. IPv4 multicast addresses are in the range 224.0.0.0 - 239.255.255.255.
- address
- The IP address to check.
Returns: true if the address is an IPv4 multicast address; otherwise, false.
public static bool IsLocal(EndPoint endPoint)
result = NetworkHelper.IsLocal(endPoint)
Determines whether the specified endpoint is local.
- endPoint
- The endpoint to check.
Returns: true if the endpoint is local; otherwise, false.
public static bool IsLocalhost(Uri url)
result = NetworkHelper.IsLocalhost(url)
Determines whether the specified Uri represents localhost.
- url
- The Uri to check.
Returns: true if the Uri is localhost; otherwise, false.
public static bool IsLocalIpAddress(EndPoint endPoint)
result = NetworkHelper.IsLocalIpAddress(endPoint)
Checks whether the specified endpoint's IP addresses include a local address.
- endPoint
- The endpoint to check.
Returns: true if a local IP address is found; otherwise, false.
public static bool IsLoopback(IPAddress address)
result = NetworkHelper.IsLoopback(address)
Determines if the specified IPAddress represents a loopback address.
- address
- The IPAddress to check.
Returns: true if the IPAddress is loopback; otherwise, false.
public static bool IsMulticastAddress(IPAddress address)
result = NetworkHelper.IsMulticastAddress(address)
Determines whether the specified IPAddress is a multicast address (IPv4 or IPv6).
- address
- The IP address to check.
Returns: true if the address is a multicast address; otherwise, false.
public static bool IsNetworkPath(string path)
result = NetworkHelper.IsNetworkPath(path)
Determines if the specified path is a network path.
- path
- Path to check.
Returns: true if the path is a network path; otherwise, false.
public static bool IsUncPath(string path)
result = NetworkHelper.IsUncPath(path)
Determines if the specified path is a UNC path (\\server\share or //server/share).
- path
- Path to check.
Returns: true if the path is a UNC path; otherwise, false.
public static bool IsUrlPath(string path)
result = NetworkHelper.IsUrlPath(path)
Determines if the specified path is a URL with a scheme (http://, https://, ftp://).
- path
- Path to check.
Returns: true if the path is a URL; otherwise, false.
public static bool IsUrlSafeChar(char ch)
result = NetworkHelper.IsUrlSafeChar(ch)
Determines whether the specified character is safe for URLs.
- ch
- The character to check.
Returns: true if the character is URL safe; otherwise, false.
public static bool IsWebDavPath(string path)
result = NetworkHelper.IsWebDavPath(path)
Determines if the specified path is a WebDAV path (dav://, davs://).
- path
- Path to check.
Returns: true if the path is a WebDAV path; otherwise, false.
public static void JoinMulticast(Socket socket, MulticastSourceAddress address)
NetworkHelper.JoinMulticast(socket, address)
Joins the specified source-specific multicast group.
- socket
- The socket to configure.
- address
- The multicast source address configuration.
public static void JoinMulticast(Socket socket, IPAddress address)
NetworkHelper.JoinMulticast(socket, address)
Joins the specified multicast group using the provided IP address.
- socket
- The socket to configure.
- address
- The multicast group IP address.
public static void LeaveMulticast(Socket socket, MulticastSourceAddress address)
NetworkHelper.LeaveMulticast(socket, address)
Leaves the specified source-specific multicast group.
- socket
- The socket to configure.
- address
- The multicast source address configuration.
public static void LeaveMulticast(Socket socket, IPAddress address)
NetworkHelper.LeaveMulticast(socket, address)
Leaves the specified multicast group using the provided IP address.
- socket
- The socket to configure.
- address
- The multicast group IP address.
public static X509Certificate2 LoadCertificate(string path, string password)
result = NetworkHelper.LoadCertificate(path, password)
Loads an X.509 certificate from a PFX/PKCS#12 file.
- path
- Path to the certificate file.
- password
- Certificate password (may be or empty).
Returns: Loaded certificate.
public static NameValueCollection ParseUrl(string url)
result = NetworkHelper.ParseUrl(url)
Parses the query string from the URL.
- url
- The URL query string.
Returns: A collection of query string parameters.
public static void SetBearer(HttpClient client, SecureString token)
NetworkHelper.SetBearer(client, token)
Sets a bearer token for authorization on the HttpClient.
- client
- The HttpClient instance.
- token
- The secure bearer token.
public static void SetStatusCodePhrase(HttpStatusCode code, string str)
NetworkHelper.SetStatusCodePhrase(code, str)
Sets a custom phrase for a specific HTTP status code.
- code
- The HTTP status code.
- str
- The phrase to associate with the status code.
public static string ToQueryString<TValue>(IEnumerable<KeyValuePair<string, TValue>> args, bool encodeValue)
result = NetworkHelper.ToQueryString(args, encodeValue)
Converts a sequence of key-value pairs into a query string.
- args
- The key-value pairs.
- encodeValue
- Whether to encode the value.
Returns: A query string representation of the key-value pairs.
public static string ToQueryString<TValue>(IEnumerable<ValueTuple<string, TValue>> args, bool encodeValue)
result = NetworkHelper.ToQueryString(args, encodeValue)
Converts a sequence of tuple key-value pairs into a query string.
- args
- The tuple key-value pairs.
- encodeValue
- Whether to encode the value.
Returns: A query string representation of the tuples.
public static SslStream ToSsl(Stream stream, SslProtocols sslProtocol, bool checkCertificateRevocation, bool validateRemoteCertificates, string targetHost, string sslCertificate, SecureString sslCertificatePassword, RemoteCertificateValidationCallback certificateValidationCallback, LocalCertificateSelectionCallback certificateSelectionCallback)
result = NetworkHelper.ToSsl(stream, sslProtocol, checkCertificateRevocation, validateRemoteCertificates, targetHost, sslCertificate, sslCertificatePassword, certificateValidationCallback, certificateSelectionCallback)
Converts the provided stream into an SSL stream with the specified options.
- stream
- The underlying stream.
- sslProtocol
- The SSL protocol to use.
- checkCertificateRevocation
- Whether to check certificate revocation.
- validateRemoteCertificates
- Whether to validate remote certificates.
- targetHost
- The target host name.
- sslCertificate
- The certificate file path.
- sslCertificatePassword
- The certificate password.
- certificateValidationCallback
- Optional certificate validation callback.
- certificateSelectionCallback
- Optional certificate selection callback.
Returns: An authenticated SslStream.
public static Encoding TryExtractEncoding(string contentType)
result = NetworkHelper.TryExtractEncoding(contentType)
Attempts to extract an Encoding from the Content-Type header.
- contentType
- The Content-Type header value.
Returns: An Encoding if found; otherwise, null.
public static SocketError? TryGetSocketError(Exception ex)
result = NetworkHelper.TryGetSocketError(ex)
Attempts to retrieve the underlying socket error from an exception.
- ex
- The exception to inspect.
Returns: The SocketError if found; otherwise, null.
public static HttpStatusCode? TryGetStatusCode(HttpRequestException ex)
result = NetworkHelper.TryGetStatusCode(ex)
Attempts to retrieve an HTTP status code from the specified HttpRequestException.
- ex
- The HttpRequestException to analyze.
Returns: The associated HttpStatusCode if found; otherwise, null.
public static bool TryParseClientIpHeader(string headerValue, IPAddress ip)
result = NetworkHelper.TryParseClientIpHeader(headerValue, ip)
Tries to parse an IP address from a proxy header value.
- headerValue
- The header value (e.g., "192.168.1.1, 10.0.0.1" or "for=192.168.1.1;proto=https").
- ip
- When this method returns, contains the parsed IP address, or null if parsing failed.
Returns: true if the IP address was successfully parsed; otherwise, false.
public static Task<T> TryRepeat<T>(RetryPolicyInfo policy, Func<CancellationToken, Task<T>> handler, int maxCount, CancellationToken cancellationToken)
result = NetworkHelper.TryRepeat(policy, handler, maxCount, cancellationToken)
Attempts to repeatedly execute a function based on the retry policy.
- policy
- The retry policy information.
- handler
- The asynchronous function to execute.
- maxCount
- The maximum number of attempts.
- cancellationToken
- The cancellation token.
Returns: The result of the function if successful.
public static string UrlEncodeToUpperCase(string url)
result = NetworkHelper.UrlEncodeToUpperCase(url)
URL encodes the string ensuring that hexadecimal values are in uppercase.
- url
- The URL to encode.
Returns: An uppercase URL encoded string.
public static string XmlEscape(string content)
result = NetworkHelper.XmlEscape(content)
Escapes special XML characters in the content.
- content
- The content to escape.
Returns: The escaped XML string.
Fields
public const int MtuSize
value = NetworkHelper.MtuSize
Gets the Maximum Transmission Unit size.