NetworkHelper

Ecng.Net

Provides various network helper extension methods.

Métodos

ApplyChromeAgent
public static void ApplyChromeAgent(HttpClient client)
NetworkHelper.ApplyChromeAgent(client)

Applies a Chrome user agent to the HttpClient.

client
The HttpClient instance.
CheckContainsUrl
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.

Devuelve: true if the URL contains one of the parts; otherwise, false.

CheckUrl
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.

Devuelve: The processed URL.

ClearUrl
public static string ClearUrl(string url)
result = NetworkHelper.ClearUrl(url)

Removes unsafe characters from the URL.

url
The URL to clear.

Devuelve: The cleared URL string.

ConnectAsync
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

Devuelve: Task

CreateHttpRequestException
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.

Devuelve: An instance of HttpRequestException.

DecodeFromHtml
public static string DecodeFromHtml(string text)
result = NetworkHelper.DecodeFromHtml(text)

Decodes the specified HTML-encoded text.

text
The text to decode.

Devuelve: The decoded string.

DecodeUrl
public static string DecodeUrl(string url)
result = NetworkHelper.DecodeUrl(url)

Decodes the specified URL.

url
The URL to decode.

Devuelve: The decoded URL string.

EncodeToHtml
public static string EncodeToHtml(string text)
result = NetworkHelper.EncodeToHtml(text)

Encodes the specified text into its HTML-encoded representation.

text
The text to encode.

Devuelve: The HTML-encoded string.

EncodeUrl
public static string EncodeUrl(string url)
result = NetworkHelper.EncodeUrl(url)

Encodes a URL using UTF8 encoding.

url
The URL to encode.

Devuelve: The encoded URL string.

EncodeUrlUpper
public static string EncodeUrlUpper(string url)
result = NetworkHelper.EncodeUrlUpper(url)

Encodes a URL ensuring uppercase encoding.

url
The URL to encode.

Devuelve: The URL encoded in uppercase.

ExcludeEmpty
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.

Devuelve: An enumerable of non-empty key-value pairs.

Format``1
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.

Devuelve: The formatted string.

GetDelay
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.

Devuelve: A TimeSpan representing the delay.

GetGravatarToken
public static string GetGravatarToken(string email)
result = NetworkHelper.GetGravatarToken(email)

Computes the Gravatar token for the specified email.

email
The email address.

Devuelve: The computed Gravatar token.

GetGravatarUrl
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.

Devuelve: The full Gravatar image URL.

IsFileUriPath
public static bool IsFileUriPath(string path)
result = NetworkHelper.IsFileUriPath(path)

Determines if the specified path is a file:// URI.

path
Path to check.

Devuelve: true if the path is a file:// URI; otherwise, false.

IsHostPortAddress
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.

Devuelve: true if the string is a host:port address; otherwise, false.

IsImage
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.

Devuelve: true if the file is an image; otherwise, false.

IsImageVector
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.

Devuelve: true if the file is a vector image; otherwise, false.

IsInSubnet
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.

Devuelve: true if the address is in the subnet; otherwise, false.

IsInternal
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.

Devuelve: true if the address is internal/non-public; otherwise, false.

IsIPv4Multicast
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.

Devuelve: true if the address is an IPv4 multicast address; otherwise, false.

IsLocal
public static bool IsLocal(EndPoint endPoint)
result = NetworkHelper.IsLocal(endPoint)

Determines whether the specified endpoint is local.

endPoint
The endpoint to check.

Devuelve: true if the endpoint is local; otherwise, false.

IsLocalhost
public static bool IsLocalhost(Uri url)
result = NetworkHelper.IsLocalhost(url)

Determines whether the specified Uri represents localhost.

url
The Uri to check.

Devuelve: true if the Uri is localhost; otherwise, false.

IsLocalIpAddress
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.

Devuelve: true if a local IP address is found; otherwise, false.

IsLoopback
public static bool IsLoopback(IPAddress address)
result = NetworkHelper.IsLoopback(address)

Determines if the specified IPAddress represents a loopback address.

address
The IPAddress to check.

Devuelve: true if the IPAddress is loopback; otherwise, false.

IsMulticastAddress
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.

Devuelve: true if the address is a multicast address; otherwise, false.

IsNetworkPath
public static bool IsNetworkPath(string path)
result = NetworkHelper.IsNetworkPath(path)

Determines if the specified path is a network path.

path
Path to check.

Devuelve: true if the path is a network path; otherwise, false.

IsUncPath
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.

Devuelve: true if the path is a UNC path; otherwise, false.

IsUrlPath
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.

Devuelve: true if the path is a URL; otherwise, false.

IsUrlSafeChar
public static bool IsUrlSafeChar(char ch)
result = NetworkHelper.IsUrlSafeChar(ch)

Determines whether the specified character is safe for URLs.

ch
The character to check.

Devuelve: true if the character is URL safe; otherwise, false.

IsWebDavPath
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.

Devuelve: true if the path is a WebDAV path; otherwise, false.

JoinMulticast
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.
JoinMulticast
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.
LeaveMulticast
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.
LeaveMulticast
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.
LoadCertificate
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).

Devuelve: Loaded certificate.

ParseUrl
public static NameValueCollection ParseUrl(string url)
result = NetworkHelper.ParseUrl(url)

Parses the query string from the URL.

url
The URL query string.

Devuelve: A collection of query string parameters.

SetBearer
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.
SetStatusCodePhrase
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.
ToQueryString``1
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.

Devuelve: A query string representation of the key-value pairs.

ToQueryString``1
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.

Devuelve: A query string representation of the tuples.

ToSsl
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.

Devuelve: An authenticated SslStream.

TryExtractEncoding
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.

Devuelve: An Encoding if found; otherwise, null.

TryGetSocketError
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.

Devuelve: The SocketError if found; otherwise, null.

TryGetStatusCode
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.

Devuelve: The associated HttpStatusCode if found; otherwise, null.

TryParseClientIpHeader
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.

Devuelve: true if the IP address was successfully parsed; otherwise, false.

TryRepeat``1
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.

Devuelve: The result of the function if successful.

UrlEncodeToUpperCase
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.

Devuelve: An uppercase URL encoded string.

XmlEscape
public static string XmlEscape(string content)
result = NetworkHelper.XmlEscape(content)

Escapes special XML characters in the content.

content
The content to escape.

Devuelve: The escaped XML string.

Campos

MtuSize
public const int MtuSize
value = NetworkHelper.MtuSize

Gets the Maximum Transmission Unit size.