Table of Contents

Class NetworkHelper

Namespace
Ecng.Net
Assembly
Ecng.Net.dll

Provides various network helper extension methods.

public static class NetworkHelper
Inheritance
NetworkHelper
Inherited Members

Fields

MtuSize

Gets the Maximum Transmission Unit size.

public const int MtuSize = 1600

Field Value

int

Methods

ApplyChromeAgent(HttpClient)

Applies a Chrome user agent to the HttpClient.

public static void ApplyChromeAgent(this HttpClient client)

Parameters

client HttpClient

The HttpClient instance.

CheckContainsUrl(string)

Checks if the URL contains any of the predefined URL parts.

public static bool CheckContainsUrl(this string url)

Parameters

url string

The URL to check.

Returns

bool

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

CheckUrl(string, bool, bool, bool)

Checks and cleans a URL by converting to Latin characters, screening, and clearing unsafe characters.

public static string CheckUrl(this string str, bool latin = true, bool screen = true, bool clear = true)

Parameters

str string

The URL string to check.

latin bool

if set to true converts characters to Latin.

screen bool

if set to true performs light screening.

clear bool

if set to true clears unsafe URL characters.

Returns

string

The processed URL.

ClearUrl(string)

Removes unsafe characters from the URL.

public static string ClearUrl(this string url)

Parameters

url string

The URL to clear.

Returns

string

The cleared URL string.

Connect(TcpClient, EndPoint)

Connects the TcpClient to the specified endpoint.

public static void Connect(this TcpClient client, EndPoint address)

Parameters

client TcpClient

The TcpClient instance.

address EndPoint

The endpoint to connect to.

CreateHttpRequestException(HttpStatusCode, string)

Creates an HttpRequestException for the specified HTTP status code and message.

public static HttpRequestException CreateHttpRequestException(this HttpStatusCode code, string message)

Parameters

code HttpStatusCode

The HTTP status code.

message string

The error message.

Returns

HttpRequestException

An instance of HttpRequestException.

DecodeFromHtml(string)

Decodes the specified HTML-encoded text.

public static string DecodeFromHtml(this string text)

Parameters

text string

The text to decode.

Returns

string

The decoded string.

DecodeUrl(string)

Decodes the specified URL.

public static string DecodeUrl(this string url)

Parameters

url string

The URL to decode.

Returns

string

The decoded URL string.

EncodeToHtml(string)

Encodes the specified text into its HTML-encoded representation.

public static string EncodeToHtml(this string text)

Parameters

text string

The text to encode.

Returns

string

The HTML-encoded string.

EncodeUrl(string)

Encodes a URL using UTF8 encoding.

public static string EncodeUrl(this string url)

Parameters

url string

The URL to encode.

Returns

string

The encoded URL string.

EncodeUrlUpper(string)

Encodes a URL ensuring uppercase encoding.

public static string EncodeUrlUpper(this string url)

Parameters

url string

The URL to encode.

Returns

string

The URL encoded in uppercase.

ExcludeEmpty(NameValueCollection)

Enumerates key-value pairs from the collection, excluding empty keys.

public static IEnumerable<(string key, string value)> ExcludeEmpty(this NameValueCollection col)

Parameters

col NameValueCollection

The name-value collection.

Returns

IEnumerable<(string key, string value)>

An enumerable of non-empty key-value pairs.

Format<T>(T, bool)

Formats the value as a string with optional URL encoding.

public static string Format<T>(this T value, bool encode)

Parameters

value T

The value to format.

encode bool

Whether to URL encode the result.

Returns

string

The formatted string.

Type Parameters

T

The type of the value.

GetDelay(RetryPolicyInfo, int)

Calculates the delay for a retry based on the current attempt number.

public static TimeSpan GetDelay(this RetryPolicyInfo policy, int attemptNumber)

Parameters

policy RetryPolicyInfo

The retry policy information.

attemptNumber int

The current attempt number.

Returns

TimeSpan

A TimeSpan representing the delay.

GetGravatarToken(string)

Computes the Gravatar token for the specified email.

public static string GetGravatarToken(this string email)

Parameters

email string

The email address.

Returns

string

The computed Gravatar token.

GetGravatarUrl(string, int)

Constructs the Gravatar URL using the provided token and size.

public static string GetGravatarUrl(this string token, int size)

Parameters

token string

The Gravatar token.

size int

The size of the Gravatar image.

Returns

string

The full Gravatar image URL.

IsConnected(Socket, int)

Determines whether the specified socket is connected.

public static bool IsConnected(this Socket socket, int timeOut = 1)

Parameters

socket Socket

The socket to check.

timeOut int

The timeout in microseconds.

Returns

bool

true if the socket is connected; otherwise, false.

IsImage(string)

Determines whether the specified file name represents an image.

public static bool IsImage(this string fileName)

Parameters

fileName string

The file name to check.

Returns

bool

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

IsImageVector(string)

Determines whether the specified file name represents a vector image.

public static bool IsImageVector(this string fileName)

Parameters

fileName string

The file name to check.

Returns

bool

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

IsInSubnet(IPAddress, string)

Determines whether the specified IPv4 or IPv6 address is part of the given subnet.

public static bool IsInSubnet(this IPAddress address, string subnetMask)

Parameters

address IPAddress

The IP address to check.

subnetMask string

The subnet mask in "IP/PrefixLength" format.

Returns

bool

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

IsLocal(EndPoint)

Determines whether the specified endpoint is local.

public static bool IsLocal(this EndPoint endPoint)

Parameters

endPoint EndPoint

The endpoint to check.

Returns

bool

true if the endpoint is local; otherwise, false.

IsLocalIpAddress(EndPoint)

Checks whether the specified endpoint's IP addresses include a local address.

public static bool IsLocalIpAddress(this EndPoint endPoint)

Parameters

endPoint EndPoint

The endpoint to check.

Returns

bool

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

IsLocalhost(Uri)

Determines whether the specified Uri represents localhost.

public static bool IsLocalhost(this Uri url)

Parameters

url Uri

The Uri to check.

Returns

bool

true if the Uri is localhost; otherwise, false.

IsLoopback(IPAddress)

Determines if the specified IPAddress represents a loopback address.

public static bool IsLoopback(this IPAddress address)

Parameters

address IPAddress

The IPAddress to check.

Returns

bool

true if the IPAddress is loopback; otherwise, false.

IsUrlSafeChar(char)

Determines whether the specified character is safe for URLs.

public static bool IsUrlSafeChar(this char ch)

Parameters

ch char

The character to check.

Returns

bool

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

JoinMulticast(Socket, MulticastSourceAddress)

Joins the specified source-specific multicast group.

public static void JoinMulticast(this Socket socket, MulticastSourceAddress address)

Parameters

socket Socket

The socket to configure.

address MulticastSourceAddress

The multicast source address configuration.

JoinMulticast(Socket, IPAddress)

Joins the specified multicast group using the provided IP address.

public static void JoinMulticast(this Socket socket, IPAddress address)

Parameters

socket Socket

The socket to configure.

address IPAddress

The multicast group IP address.

LeaveMulticast(Socket, MulticastSourceAddress)

Leaves the specified source-specific multicast group.

public static void LeaveMulticast(this Socket socket, MulticastSourceAddress address)

Parameters

socket Socket

The socket to configure.

address MulticastSourceAddress

The multicast source address configuration.

LeaveMulticast(Socket, IPAddress)

Leaves the specified multicast group using the provided IP address.

public static void LeaveMulticast(this Socket socket, IPAddress address)

Parameters

socket Socket

The socket to configure.

address IPAddress

The multicast group IP address.

ParseUrl(string)

Parses the query string from the URL.

public static NameValueCollection ParseUrl(this string url)

Parameters

url string

The URL query string.

Returns

NameValueCollection

A collection of query string parameters.

Read(Socket, byte[], int, int)

Reads the specified number of bytes from the socket into the provided buffer.

public static void Read(this Socket socket, byte[] buffer, int offset, int len)

Parameters

socket Socket

The source socket.

buffer byte[]

The buffer to store the data.

offset int

The offset in the buffer.

len int

The number of bytes to read.

SetBearer(HttpClient, SecureString)

Sets a bearer token for authorization on the HttpClient.

public static void SetBearer(this HttpClient client, SecureString token)

Parameters

client HttpClient

The HttpClient instance.

token SecureString

The secure bearer token.

SetStatusCodePhrase(HttpStatusCode, string)

Sets a custom phrase for a specific HTTP status code.

public static void SetStatusCodePhrase(HttpStatusCode code, string str)

Parameters

code HttpStatusCode

The HTTP status code.

str string

The phrase to associate with the status code.

ToQueryString<TValue>(IEnumerable<KeyValuePair<string, TValue>>, bool)

Converts a sequence of key-value pairs into a query string.

public static string ToQueryString<TValue>(this IEnumerable<KeyValuePair<string, TValue>> args, bool encodeValue = false)

Parameters

args IEnumerable<KeyValuePair<string, TValue>>

The key-value pairs.

encodeValue bool

Whether to encode the value.

Returns

string

A query string representation of the key-value pairs.

Type Parameters

TValue

The type of the value.

ToQueryString<TValue>(IEnumerable<(string key, TValue value)>, bool)

Converts a sequence of tuple key-value pairs into a query string.

public static string ToQueryString<TValue>(this IEnumerable<(string key, TValue value)> args, bool encodeValue = false)

Parameters

args IEnumerable<(string key, TValue value)>

The tuple key-value pairs.

encodeValue bool

Whether to encode the value.

Returns

string

A query string representation of the tuples.

Type Parameters

TValue

The type of the value.

ToSsl(Stream, SslProtocols, bool, bool, string, string, SecureString, RemoteCertificateValidationCallback, LocalCertificateSelectionCallback)

Converts the provided stream into an SSL stream with the specified options.

public static SslStream ToSsl(this Stream stream, SslProtocols sslProtocol, bool checkCertificateRevocation, bool validateRemoteCertificates, string targetHost, string sslCertificate, SecureString sslCertificatePassword, RemoteCertificateValidationCallback certificateValidationCallback = null, LocalCertificateSelectionCallback certificateSelectionCallback = null)

Parameters

stream Stream

The underlying stream.

sslProtocol SslProtocols

The SSL protocol to use.

checkCertificateRevocation bool

Whether to check certificate revocation.

validateRemoteCertificates bool

Whether to validate remote certificates.

targetHost string

The target host name.

sslCertificate string

The certificate file path.

sslCertificatePassword SecureString

The certificate password.

certificateValidationCallback RemoteCertificateValidationCallback

Optional certificate validation callback.

certificateSelectionCallback LocalCertificateSelectionCallback

Optional certificate selection callback.

Returns

SslStream

An authenticated SslStream.

TryExtractEncoding(string)

Attempts to extract an Encoding from the Content-Type header.

public static Encoding TryExtractEncoding(this string contentType)

Parameters

contentType string

The Content-Type header value.

Returns

Encoding

An Encoding if found; otherwise, null.

TryGetSocketError(Exception)

Attempts to retrieve the underlying socket error from an exception.

public static SocketError? TryGetSocketError(this Exception ex)

Parameters

ex Exception

The exception to inspect.

Returns

SocketError?

The SocketError if found; otherwise, null.

TryGetStatusCode(HttpRequestException)

Attempts to retrieve an HTTP status code from the specified HttpRequestException.

public static HttpStatusCode? TryGetStatusCode(this HttpRequestException ex)

Parameters

ex HttpRequestException

The HttpRequestException to analyze.

Returns

HttpStatusCode?

The associated HttpStatusCode if found; otherwise, null.

TryRepeat<T>(RetryPolicyInfo, Func<Task<T>>, int, CancellationToken)

Attempts to repeatedly execute a function based on the retry policy.

public static Task<T> TryRepeat<T>(this RetryPolicyInfo policy, Func<Task<T>> handler, int maxCount, CancellationToken cancellationToken)

Parameters

policy RetryPolicyInfo

The retry policy information.

handler Func<Task<T>>

The asynchronous function to execute.

maxCount int

The maximum number of attempts.

cancellationToken CancellationToken

The cancellation token.

Returns

Task<T>

The result of the function if successful.

Type Parameters

T

The type of the result.

UrlEncodeToUpperCase(string)

URL encodes the string ensuring that hexadecimal values are in uppercase.

public static string UrlEncodeToUpperCase(this string url)

Parameters

url string

The URL to encode.

Returns

string

An uppercase URL encoded string.

Wait(Socket, int)

Waits for data availability on the socket.

public static bool Wait(this Socket socket, int timeOut)

Parameters

socket Socket

The socket to wait on.

timeOut int

The timeout in microseconds.

Returns

bool

true if data is available; otherwise, false.

XmlEscape(string)

Escapes special XML characters in the content.

public static string XmlEscape(this string content)

Parameters

content string

The content to escape.

Returns

string

The escaped XML string.