• NeonSDK
  • NeonKUBE
Search Results for

    Show / Hide Table of Contents
    • Neon
      • Build
    • Neon.Blazor
      • BlazorHelper
      • BodyOutlet
      • ClientRenderContext
      • DOMRectReadOnly
      • EventHandlers
      • FileDownloader
      • HtmlElement
      • IRenderContext
      • IntersectionChangedEventArgs
      • IntersectionObserver
      • IntersectionObserverContext
      • MobileDetector
      • NeonBlazorExtensions
      • ServerRenderContext
      • SwipeDirection
      • SwipeHandler
    • Neon.Blazor.Analyzers
      • SvgGenerator
      • SvgGenerator.Svg
    • Neon.BuildInfo
      • ThisAssembly
      • ThisAssembly.Git
      • ThisAssembly.Git.BaseVersion
      • ThisAssembly.Git.SemVer
    • Neon.CSharp
      • CSharpHelper
      • CompilerErrorException
      • MetadataReferences
    • Neon.Cassandra
      • KeyspaceStatus
      • RowSetExtensions
      • SchemaManager
      • SchemaManagerException
      • SchemaStatus
      • SessionExtensions
    • Neon.Collections
      • ArgDictionary
      • Bits
      • IObjectDictionary
      • NiceDictionary<TKey, TValue>
      • ObjectDictionary
    • Neon.Common
      • AppDomainExtensions
      • Block
      • BlockArray
      • ByteEncoding
      • ByteUnits
      • CommandLine
      • CommandLine.OptionDefinition
      • CommandLine.Redactor
      • CpuArchitecture
      • Credentials
      • DateTimeExtensions
      • EnumExtensions
      • EnvironmentParser
      • EnvironmentParser.Parser<T>
      • EnvironmentParser.Validator<T>
      • EnvironmentParser.VariableSource
      • ExceptionExtensions
      • ExecuteException
      • ExecuteResponse
      • GlobPattern
      • HexDumpOption
      • HttpClientExtensions
      • HttpResponseMessageExtensions
      • IEnumerableExtensions
      • ILabeled
      • IOExtensions
      • IServiceContainer
      • IStaticDirectoryExtensions
      • LabelSelector
      • LabelSelectorOptions
      • LabelSelector<TItem>
      • NeonAssemblyExtensions
      • NeonExtendedHelper
      • NeonHelper
      • NetFramework
      • NewtonsoftExtensions
      • NotReadyException
      • ProcessExtensions
      • ProgramEntrypoint
      • ProgramEntrypointAsync
      • ProgramExitException
      • ProgramRunner
      • RandomExtensions
      • ReflectionExtensions
      • SemanticVersion
      • ServiceContainer
      • StaticZipOptions
      • StringBuilderExtensions
      • StringExtensions
      • Stub
      • Stub.Value
      • TaskExtensions
      • TimeSpanExtensions
      • ToolException
      • TriState
      • WeakEventController
      • WindowsEdition
      • WindowsFeatureStatus
      • YamlDotNetExtensions
    • Neon.Cryptography
      • AesCipher
      • CryptoExtensions
      • CryptoHelper
      • NeonVault
      • Wildcard
    • Neon.Csv
      • CsvReader
      • CsvTableReader
      • CsvTableWriter
      • CsvWriter
    • Neon.Data
      • DateTimeJsonConverter
      • DateTimeOffsetJsonConverter
      • IEnhancedJsonConverter
      • IGeneratedServiceClient
      • IPersistableType
      • IPersistableType<T>
      • IRoundtripData
      • IntegerEnumConverter<TEnum>
      • NotifyPropertyChanged
      • RoundtripDataFactory
      • RoundtripDataHelper
      • TimeSpanJsonConverter
      • VersionJsonConverter
    • Neon.Deployment
      • AwsCli
      • DeploymentException
      • DeploymentHelper
      • DownloadManifest
      • DownloadPart
      • DownloadProgressDelegate
      • DownloadProgressType
      • GitHub
      • GitHubActionsApi
      • GitHubPackage
      • GitHubPackageApi
      • GitHubPackageType
      • GitHubPackageVersion
      • GitHubPackageVisibility
      • GitHubReleaseApi
      • GitHubRepoPath
      • GitHubTagApi
      • IProfileClient
      • IProfileRequest
      • IProfileResponse
      • MaintainerProfile
      • NotifyClient
      • OnePassword
      • OnePasswordException
      • ProfileException
      • ProfileHandlerResult
      • ProfileRequest
      • ProfileResponse
      • ProfileServer
      • ProfileStatus
      • XenServer
    • Neon.Deployment.CodeSigning
      • AzureProfile
      • CodeSigner
      • UsbTokenProfile
    • Neon.Diagnostics
      • AssertException
      • ConfigExtensions
      • ConsoleJsonLogExporter
      • ConsoleJsonLogExporterOptions
      • ConsoleTextLogExporter
      • ConsoleTextLogExporterOptions
      • ExceptionInfo
      • FileLogExporter
      • FileLogExporterFormat
      • FileLogExporterOptions
      • LogAsTraceProcessor
      • LogAsTraceProcessorOptions
      • LogAttributeNames
      • LogAttributes
      • LogEvent
      • LogEventInterceptor
      • LoggerExtensions
      • NullLogger
      • TelemetryHub
      • TelemetrySpanEventNames
      • TelemetrySpanExtensions
    • Neon.Docker
      • DockerClient
      • DockerNetwork
      • DockerNetworkContainer
      • DockerNetworkIpam
      • DockerNode
      • DockerNodeManagerStatus
      • DockerResponse
      • DockerSettings
      • DockerVolume
      • NetworkCreateResponse
      • ServiceBindOptions
      • ServiceConfig
      • ServiceContainerSpec
      • ServiceCredentialSpec
      • ServiceDetails
      • ServiceDiscreteResourceSpec
      • ServiceDnsConfig
      • ServiceEndpoint
      • ServiceEndpointMode
      • ServiceEndpointPortConfig
      • ServiceEndpointSpec
      • ServiceFile
      • ServiceGenericResources
      • ServiceGlobalSchedulingMode
      • ServiceHealthCheck
      • ServiceIsolationMode
      • ServiceListResponse
      • ServiceLogDriver
      • ServiceMode
      • ServiceMount
      • ServiceMountBindPropagation
      • ServiceMountConsistency
      • ServiceMountType
      • ServiceNamedResourceSpec
      • ServiceNetwork
      • ServicePlacement
      • ServicePlacementPreferences
      • ServicePlacementSpreadSettings
      • ServicePlatform
      • ServicePortMode
      • ServicePortProtocol
      • ServicePrivileges
      • ServiceReplicatedSchedulingMode
      • ServiceResourceSettings
      • ServiceResources
      • ServiceRestartCondition
      • ServiceRestartPolicy
      • ServiceRollbackConfig
      • ServiceRollbackFailureAction
      • ServiceRollbackOrder
      • ServiceSELinuxContext
      • ServiceSchedulingMode
      • ServiceSecret
      • ServiceSpec
      • ServiceTaskTemplate
      • ServiceTmpfsOptions
      • ServiceUpdateConfig
      • ServiceUpdateFailureAction
      • ServiceUpdateOrder
      • ServiceUpdateState
      • ServiceUpdateStatus
      • ServiceVersion
      • ServiceVirtualIP
      • ServiceVolumeDriverConfig
      • ServiceVolumeOptions
      • VolumeListResponse
    • Neon.GitHub
      • GitExtensions
      • GitHubCredentials
      • GitHubRepo
      • LocalRepoApi
      • NoLocalRepositoryException
      • RemoteRepoApi
      • RemoteRepoBranchApi
      • RemoteRepoIssueApi
      • RemoteRepoIssueCommentApi
      • RemoteRepoPath
      • RemoteRepoReleaseApi
      • RemoteRepoTagApi
    • Neon.HyperV
      • HyperVClient
      • HyperVDriverType
      • HyperVException
      • NetAdapter
      • VirtualDrive
      • VirtualIPAddress
      • VirtualMachine
      • VirtualMachineNetworkAdapter
      • VirtualMachineState
      • VirtualNat
      • VirtualSwitch
      • VirtualSwitchType
    • Neon.IO
      • BlockStream
      • FixedLengthStream
      • IStaticDirectory
      • IStaticFile
      • LineEnding
      • LinuxPath
      • LinuxPermissions
      • PreprocessReader
      • RelayStream
      • StaticDirectoryBase
      • StaticFileBase
      • SubStream
      • TempFile
      • TempFolder
    • Neon.JsonConverters
      • JsonDateTimeConverter
      • JsonGenericConverter<T>
      • JsonNullableDateTimeConverter
    • Neon.ModelGen
      • ActionResult<T>
      • ApiVersion
      • ApiVersionAttribute
      • BodyStreamAttribute
      • ControllerValidationAttribute
      • DataModelAttribute
      • EnumMember
      • FromBodyAttribute
      • FromHeaderAttribute
      • FromQueryAttribute
      • FromRouteAttribute
      • GeneratedClientAttribute
      • GeneratedMethodAttribute
      • GeneratedParamAttribute
      • HashSourceAttribute
      • HttpAttribute
      • HttpDeleteAttribute
      • HttpGetAttribute
      • HttpHeadAttribute
      • HttpOptionsAttribute
      • HttpPatchAttribute
      • HttpPostAttribute
      • HttpPutAttribute
      • IActionResult
      • ModelGenerator
      • ModelGeneratorOutput
      • ModelGeneratorSettings
      • NoCodeGenAttribute
      • NoControllerValidationAttribute
      • PassAs
      • PersistableAttribute
      • PersistableKeyAttribute
      • RouteAttribute
      • ServiceModelAttribute
      • TargetAttribute
      • UxFrameworks
    • Neon.Net
      • HttpApiException
      • HttpException
      • JsonClient
      • JsonClientPayload
      • JsonResponse
      • Jwt
      • LocalHostSection
      • NetConst
      • NetHelper
      • NetworkCidr
      • NetworkConfiguration
      • NetworkException
      • NetworkPorts
      • Pinger
      • ReachableHost
      • ReachableHostMode
      • StreamDocument
    • Neon.Postgres
      • ConnectionExtensions
      • DatabaseStatus
      • PreparedCommand
      • ReaderAsyncEnumerator
      • ReaderEnumerator
      • ReaderExtensions
      • SchemaManager
      • SchemaManagerException
      • SchemaStatus
    • Neon.Retry
      • ExponentialRetryPolicy
      • IRetryPolicy
      • LinearRetryPolicy
      • NoRetryPolicy
      • RetryPolicy
      • RetryPolicyBase
      • RetryTransientArgs
      • TransientDetector
      • TransientException
    • Neon.Roslyn
      • DisplayFormat
      • DocumentationComment
      • DocumentationItem
      • MetadataLoadContext
      • RoslynAssembly
      • RoslynConstructorInfo
      • RoslynCustomAttributeData
      • RoslynExtensions
      • RoslynFieldInfo
      • RoslynMethodInfo
      • RoslynParameterInfo
      • RoslynPropertyInfo
      • RoslynType
      • SharedUtilities
    • Neon.Roslyn.Xunit
      • AdditionalSourceText
      • CompilationOptions
      • CompilationOptionsProvider
      • TestCompilation
      • TestCompilationAssertions
      • TestCompilationBuilder
      • TestCompilationBuilderExtensions
      • TestCompilationExtensions
    • Neon.SSH
      • CommandBundle
      • CommandFile
      • CommandResponse
      • HostFolders
      • IBashCommandFormatter
      • ILinuxSshProxy
      • LinuxDiskInfo
      • LinuxDiskPartition
      • LinuxSshProxy
      • LinuxSshProxy<TMetadata>
      • NamespaceDoc
      • RemoteCommandException
      • RunOptions
      • SshCredentials
      • SshExtensions
      • SshProxyException
    • Neon.Service
      • LogMetricsProcessor
      • MetricsMode
      • MetricsOptions
      • NeonService
      • NeonServiceOptions
      • NeonServiceStatus
      • OtelConfigExtensions
      • OtlpCollectorChecker
      • ProcessTerminator
      • ServiceApiContact
      • ServiceApiInfo
      • ServiceApiLicense
      • ServiceDependencies
      • ServiceDescription
      • ServiceEndpoint
      • ServiceEndpointProtocol
      • ServiceEndpoints
      • ServiceMap
    • Neon.SignalR
      • DependencyInjectionExtensions
      • DnsCache
      • GroupAction
      • GroupCommand
      • IDnsCache
      • Invocation
      • NatsHubLifetimeManager<THub>
      • ProxyConfig
      • ServiceCollectionExtensions
      • ServiceDiscovey
      • SignalrProxyMiddleware
      • SignalrProxyMiddlewareExtensions
      • TracerProviderBuilderExtensions
    • Neon.Tailwind
      • ClickOffEventHandler
      • ComponentEventArgs<TSender>
      • ComponentEventArgs<TSender, TEventArgs>
      • DisclosureState
      • EventHandlerComponentBase<TComponent>
      • HeadlessButton
      • HeadlessDialog
      • HeadlessDialogPanel
      • HeadlessDisclosure
      • HeadlessDisclosureButton
      • HeadlessDisclosurePanel
      • HeadlessListboxButton<TValue>
      • HeadlessListboxLabel<TValue>
      • HeadlessListboxOption<TValue>
      • HeadlessListboxOptions<TValue>
      • HeadlessListbox<TValue>
      • HeadlessMenu
      • HeadlessMenuButton
      • HeadlessMenuItem
      • HeadlessMenuItems
      • HeadlessSwitch
      • HeadlessSwitchGroup
      • HeadlessSwitchLabel
      • IPortalBinder
      • KeyDownEventHandler
      • KeyboardKey
      • ListboxFocus
      • ListboxState
      • MenuFocus
      • MenuState
      • Portal
      • PortalBinder
      • PortalContent
      • SearchAssistant
      • TailwindExtensions
      • Transition
      • TransitionGroup
      • TransitionState
    • Neon.Tasks
      • Async
      • AsyncAutoResetEvent
      • AsyncManualResetEvent
      • AsyncMutex
      • AsyncPeriodicTask
      • AsyncReaderWriterLock
      • AsyncReentrantMutex
      • AsyncTimer
      • IAsyncFuture
      • IAsyncFuture<T>
      • NonDisposableTask
      • NonDisposableTask<T>
      • SyncContext
      • SyncContextMode
    • Neon.Temporal
      • ActivityHelper
      • ActivityLogEnricher
      • TemporalEnricherTagNames
      • WorkflowLogEnricher
    • Neon.Time
      • GatedTimer
      • GoDuration
      • PolledTimer
      • RecurringTimer
      • RecurringTimerType
      • SysTime
      • TimeOfDay
    • Neon.WSL
      • Wsl2Proxy
    • Neon.Web
      • AesProtector
      • DataProtectionExtensions
      • NeonController
      • NeonControllerBase
      • RoundTripJsonInputFormatter
      • RoundTripJsonOutputFormatter
      • TracerProviderBuilderExtensions
      • WebHelper
    • Neon.WinTTY
      • ConsoleTTY
    • Neon.Windows
      • MEMORYSTATUSEX
      • PowerShellException
      • Win32
    • Neon.XenServer
      • IXenClient
      • XenClient
      • XenClient.MachineOperations
      • XenClient.StorageOperations
      • XenClient.TemplateOperations
      • XenException
      • XenHostInfo
      • XenObject
      • XenResponse
      • XenStorageRepository
      • XenTempIso
      • XenTemplate
      • XenVirtualDisk
      • XenVirtualMachine
      • XenVmPowerState
    • Neon.Xunit
      • AnsiblePlayResults
      • AnsiblePlayer
      • AnsibleTaskResult
      • AspNetFixture
      • BasicFixture
      • CodeFixture
      • CollectionComparer<T>
      • ComposedFixture
      • ContainerFixture
      • ContainerLimits
      • DockerComposeFixture
      • DockerFixture
      • DockerFixture.ConfigInfo
      • DockerFixture.ContainerInfo
      • DockerFixture.NetworkInfo
      • DockerFixture.SecretInfo
      • DockerFixture.ServiceInfo
      • DockerFixture.StackDefinition
      • DockerFixture.StackInfo
      • DockerFixture.StackService
      • EnvironmentFixture
      • HostsFixture
      • ITestFixture
      • IncompatibleServiceException
      • MaintainerFactAttribute
      • MaintainerTheoryAttribute
      • MockHttpServer
      • MockHttpServerExtensions
      • NatsFixture
      • NatsStreamingFixture
      • NeonServiceFixture<TService>
      • PlatformFactAttribute
      • RepeatAttribute
      • TargetPlatforms
      • TestArea
      • TestCollection
      • TestContext
      • TestFixture
      • TestFixtureStatus
      • TestHelper
      • TestHttpClient
      • TestOutputWriter
      • TestTrait
      • XunitExtensions
    • Neon.Xunit.YugaByte
      • YugaByteFixture
    • Neon.YugaByte
      • YugaByteHelper

    Class NetHelper

    Useful network related utilities.

    Inheritance
    object
    NetHelper
    Namespace: Neon.Net
    Assembly: Neon.Common.dll
    Syntax
    public static class NetHelper

    Methods

    AddressEquals(IPAddress, IPAddress)

    Determines whether two IP addresses are equal.

    Declaration
    public static bool AddressEquals(IPAddress address1, IPAddress address2)
    Parameters
    Type Name Description
    IPAddress address1

    Address 1.

    IPAddress address2

    Address 2.

    Returns
    Type Description
    bool

    true if the addresses are equal.

    AddressIncrement(IPAddress, int)

    Increments an IPv4 address by adding an integer value.

    Declaration
    public static IPAddress AddressIncrement(IPAddress address, int incrementBy = 1)
    Parameters
    Type Name Description
    IPAddress address

    The input IPv4 address.

    int incrementBy

    The increment value (defaults to +1).

    Returns
    Type Description
    IPAddress

    The next address or 0.0.0.0 when we wrap-around the address space.

    Exceptions
    Type Condition
    NotSupportedException

    Thrown for non-IPv4 addresses.

    AddressToUint(IPAddress)

    Converts an IPv4 address into a 32-bit unsigned integer equivalent.

    Declaration
    public static uint AddressToUint(IPAddress address)
    Parameters
    Type Name Description
    IPAddress address

    The input IPv4 address.

    Returns
    Type Description
    uint

    The 32-bit unsigned integer equivalent.

    ComputeMSS(int, bool)

    Computes the TCP maximum segment size for a given MTU, optionally taking a VXLAN wrapper headers into account.

    Declaration
    public static int ComputeMSS(int mtu = 1500, bool vxLan = false)
    Parameters
    Type Name Description
    int mtu

    Specifies the target MTU (defaults to DefaultMTU).

    bool vxLan

    Optionally indicates that traffic is routed via a VXLAN.

    Returns
    Type Description
    int

    The maximum segment size in bytes.

    DeleteArpEntry(IPAddress)

    Removes the cached ARP entry for an IP address if it's present.

    note

    This is currently supported only for Windows.

    Declaration
    public static void DeleteArpEntry(IPAddress address)
    Parameters
    Type Name Description
    IPAddress address

    Specifies the IP address being removed from the ARP cache.

    Exceptions
    Type Condition
    NotSupportedException

    Thrown when the current platform is not supported.

    EnsureSuccess(HttpStatusCode, string)

    Ensures that the status code passed indicates an HTTP request completed successfully.

    note

    Status codes between 200-299 are considered to indicate success.

    Declaration
    public static HttpStatusCode EnsureSuccess(HttpStatusCode statusCode, string reasonPhrase = null)
    Parameters
    Type Name Description
    HttpStatusCode statusCode

    Specifies the status code.

    string reasonPhrase

    Optionally specifies the reason phrase to be included in any exception thrown.

    Returns
    Type Description
    HttpStatusCode

    The status code passed.

    Exceptions
    Type Condition
    HttpException

    Thrown for non-success status codes.

    GetAddressUriHost(IPAddress)

    Converts an IPAddress into a host name suitable for using as a Uri host name. For IPv4 addresses, this just returns the address as a string. For IPv6 address, this returns the address surrounded by "[...]" to make it compatible with URI standards.

    Declaration
    public static string GetAddressUriHost(IPAddress address)
    Parameters
    Type Name Description
    IPAddress address

    The IP address.

    Returns
    Type Description
    string

    The host name suitable for including in a URI.

    Exceptions
    Type Condition
    NotSupportedException

    Thrown for non IPv4 or IPv6 addresses.

    GetArpFlatTableAsync()

    Returns a flattened ARP table for the current machine. This is just a dictionary keyed by IP addresses mapping to the cached MAC address.

    note

    This is currently supported only for Windows.

    Declaration
    public static Task<Dictionary<IPAddress, byte[]>> GetArpFlatTableAsync()
    Returns
    Type Description
    Task<Dictionary<IPAddress, byte[]>>

    The IP/MAC dictionary.

    Exceptions
    Type Condition
    NotSupportedException

    Thrown when the current platform is not supported.

    GetArpTableAsync()

    Returns the ARP table for the current machine.

    note

    This is currently supported only for Windows.

    Declaration
    public static Task<Dictionary<IPAddress, Dictionary<IPAddress, byte[]>>> GetArpTableAsync()
    Returns
    Type Description
    Task<Dictionary<IPAddress, Dictionary<IPAddress, byte[]>>>

    A dictionary of dictionaries, with the first level keyed by network interface IP address, returning a dictionary relating IP addresses to MAC addresses for that interface.

    Exceptions
    Type Condition
    NotSupportedException

    Thrown when the current platform is not supported.

    GetConnectedGatewayAddress()

    Returns an upstream getway address for the network interface returned by GetConnectedInterface().

    Declaration
    public static IPAddress GetConnectedGatewayAddress()
    Returns
    Type Description
    IPAddress

    The IP address or null if there doesn't appear to be a connected network interface.

    Remarks

    This works via a somewhat fragile heuristic. We list all network interfaces, filter out those that are loopback, TAP interfaces, Hyper-V switches as well as any that aren't up and then return the highest speed interface from any remaining interfaces.

    This may not work as expected for machines with multiple active connections to different networks.

    GetConnectedInterface()

    Returns a connected network interface with an IPv4 address.

    Declaration
    public static NetworkInterface GetConnectedInterface()
    Returns
    Type Description
    NetworkInterface

    The connected interface or null if there doesn't appear to be a connected network interface.

    Remarks

    This works via a somewhat fragile heuristic. We list all network interfaces, filter out those that are loopback, TAP interfaces, Hyper-V switches as well as any that aren't up and then return the highest speed interface from any remaining interfaces.

    This may not work as expected for machines with multiple active connections to different networks.

    GetMacAddressAsync(IPAddress)

    Attempts to fetch the MAC address associated with an IP address.

    note

    This is currently supported only for Windows.

    Declaration
    public static Task<byte[]> GetMacAddressAsync(IPAddress address)
    Parameters
    Type Name Description
    IPAddress address

    Specifies the IP address.

    Returns
    Type Description
    Task<byte[]>

    The MAC address as a byte array or null when no MAC address could be located.

    Remarks

    This works by sending an ICMP ping to address and then using the arp command line tool to fetch the local ARP table in an attempt to locate the MAC address. The idea here is that the ping should cause the target's MAC address to be added to the ARP table when the target is running and is on the local network.

    note

    The first MAC address for the IP address found will be returned.

    Exceptions
    Type Condition
    NotSupportedException

    Thrown when the current platform is not supported.

    GetNetworkConfiguration()

    Returns basic information about the current network connection including the machine's routable IP address, the network CIDR and gateway as well as the DNS server addresses.

    Declaration
    public static NetworkConfiguration GetNetworkConfiguration()
    Returns
    Type Description
    NetworkConfiguration

    A NetworkConfiguration with the information or null when the computer doesn't appear to be connected to a network.

    Remarks

    This implementation is somewhat fragile because it relies on GetRoutableIpAddress() which uses heuristics to try to identify a suitable connected network. This may not work as expected for machines with multiple active connections to different networks.

    GetReachableHost(IEnumerable<string>, ReachableHostMode)

    Pings one or more hostnames or IP addresses in parallel to identify one that appears to be online and reachable via the network (because it answers a ping).

    Declaration
    public static ReachableHost GetReachableHost(IEnumerable<string> hosts, ReachableHostMode failureMode = ReachableHostMode.ReturnFirst)
    Parameters
    Type Name Description
    IEnumerable<string> hosts

    The hostname or IP addresses to be tested.

    ReachableHostMode failureMode

    Specifies what should happen when there are no reachable hosts.
    This defaults to ReturnFirst.

    Returns
    Type Description
    ReachableHost

    A ReachableHost instance describing the host or null.

    Exceptions
    Type Condition
    NetworkException

    Thrown if no hosts are reachable and failureMode is passed as Throw.

    GetReachableHosts(IEnumerable<string>)

    Pings one or more hostnames or IP addresses in parallel to identify those that appear to be online and reachable via the network (because it answers a ping).

    Declaration
    public static IEnumerable<ReachableHost> GetReachableHosts(IEnumerable<string> hosts)
    Parameters
    Type Name Description
    IEnumerable<string> hosts

    The hostname or IP addresses to be tested.

    Returns
    Type Description
    IEnumerable<ReachableHost>

    The ReachableHost instances describing the reachable hosts (if any).

    GetRoutableIpAddress()

    Returns a routable (non-loopback) IPv4 address for the current machine.

    note

    This returns a routable IP address from the network interface returned by GetConnectedInterface() when there is a connected interface.

    Declaration
    public static IPAddress GetRoutableIpAddress()
    Returns
    Type Description
    IPAddress

    The IP address or null if there doesn't appear to be a connected network interface.

    Remarks

    This works via a somewhat fragile heuristic. We list all network interfaces, filter out those that are loopback, TAP interfaces, Hyper-V switches as well as any that aren't up and then return the highest speed interface from any remaining interfaces.

    This may not work as expected for machines with multiple active connections to different networks.

    GetUnusedTcpPort(int, int, IPAddress)

    Returns a free TCP port for a local network interface within a given range of ports.

    Declaration
    public static int GetUnusedTcpPort(int startPort, int endPort, IPAddress address = null)
    Parameters
    Type Name Description
    int startPort

    The first port to check

    int endPort

    The last port to check.

    IPAddress address

    Optionally specifies the target interface's IP address. This defaults to Any where an unused port will be returned that is available on all network interfaces.

    Returns
    Type Description
    int

    The free port number.

    Remarks
    note

    The behavior when GetUnusedTcpPort(IPAddress) is called multiple times without actually listening on the ports is somewhat undefined.

    We believe most operating systems won't return the same port again for a while (perhaps a few minutes) so you're probably safe retrieving a few unused ports before using them for testing and other non-production purposes.

    Production code should begin listening on and unused ports immediately after retrieving one. This will ensure that the unused ports returned will be unique and also help avoid having another application grab the port before you have a chance to listen on it.

    Exceptions
    Type Condition
    NetworkException

    Thrown when there are no available ports.

    GetUnusedTcpPort(IPAddress)

    Returns a free TCP port for a local network interface.

    Declaration
    public static int GetUnusedTcpPort(IPAddress address = null)
    Parameters
    Type Name Description
    IPAddress address

    Optionally specifies the target interface's IP address. This defaults to Any where an unused port will be returned that is available on all network interfaces.

    Returns
    Type Description
    int

    The free port number.

    Remarks
    note

    The behavior when GetUnusedTcpPort(IPAddress) is called multiple times without actually listening on the ports is somewhat undefined.

    We believe most operating systems won't return the same port again for a while (perhaps a few minutes) so you're probably safe retrieving a few unused ports before using them for testing and other non-production purposes.

    Production code should begin listening on and unused ports immediately after retrieving one. This will ensure that the unused ports returned will be unique and also help avoid having another application grab the port before you have a chance to listen on it.

    Exceptions
    Type Condition
    NetworkException

    Thrown when there are no available ports.

    IsValidDnsHost(string)

    Verifies that a string is a valid DNS hostname.

    Declaration
    public static bool IsValidDnsHost(string host)
    Parameters
    Type Name Description
    string host

    The hostname being tested.

    Returns
    Type Description
    bool

    true if the hostname is valid.

    IsValidDnsLabel(string)

    Verifies that a string is a valid DNS label.

    Declaration
    public static bool IsValidDnsLabel(string label)
    Parameters
    Type Name Description
    string label

    The label being tested.

    Returns
    Type Description
    bool

    IsValidPort(int)

    Determines whether an integer is a valid network port number.

    Declaration
    public static bool IsValidPort(int port)
    Parameters
    Type Name Description
    int port

    The port.

    Returns
    Type Description
    bool

    true if the port is valid.

    ListLocalHostsSections()

    Lists the names of the local host sections.

    Declaration
    public static IEnumerable<LocalHostSection> ListLocalHostsSections()
    Returns
    Type Description
    IEnumerable<LocalHostSection>

    The section names converted to uppercase.

    ModifyLocalHosts(string, Dictionary<string, IPAddress>)

    Used to modify the $/etc/hosts file used by the DNS resolver for testing, debugging and possibly other purposes.

    note

    WARNING: Modifying the hosts file will impact all processes on the system, not just the current process.

    Declaration
    public static void ModifyLocalHosts(string section, Dictionary<string, IPAddress> hostEntries = null)
    Parameters
    Type Name Description
    string section

    Specifies the string to use to delimit the host names section. This is required and must be a non-empty string consisting of up to 63 non-control ASCII characters. Section names are case sensitive.

    Dictionary<string, IPAddress> hostEntries

    A dictionary mapping the hostnames to an IP address or null.

    Remarks
    note

    This method requires elevated administrative privileges.

    This method adds or removes a temporary section of host entry definitions delimited by special comment lines. When hostEntries is non-null and non-empty, the section will be added or updated. Otherwise, the section will be removed.

    You can remove all host sections by passing both hostEntries and section as null.

    ParseIPv4Address(string)

    Parses an IPv4 address.

    Declaration
    public static IPAddress ParseIPv4Address(string input)
    Parameters
    Type Name Description
    string input

    The address text.

    Returns
    Type Description
    IPAddress

    The IPAddress.

    Exceptions
    Type Condition
    FormatException

    Thrown for an invalid address.

    ParseIPv4Endpoint(string)

    Parses an IPv4 endpoint from a string.

    Declaration
    public static IPEndPoint ParseIPv4Endpoint(string input)
    Parameters
    Type Name Description
    string input

    The input.

    Returns
    Type Description
    IPEndPoint

    The parsed IPEndPoint.

    Exceptions
    Type Condition
    FormatException

    Thrown if the input is not valid.

    ParseIPv6Address(string)

    Parses an IPv6 address.

    Declaration
    public static IPAddress ParseIPv6Address(string input)
    Parameters
    Type Name Description
    string input

    The address text.

    Returns
    Type Description
    IPAddress

    The IPAddress.

    Exceptions
    Type Condition
    FormatException

    Thrown for an invalid address.

    TcpPortIsFree(int, IPAddress)

    Checks to see whether a TCP port is free on a given IP address.

    Declaration
    public static bool TcpPortIsFree(int port, IPAddress address = null)
    Parameters
    Type Name Description
    int port

    The port number.

    IPAddress address

    The optional IP address. If not specified, defaults to Any.

    Returns
    Type Description
    bool

    ToAwsS3Uri(string)

    Converts an S3 or standard HTTPS URI into an S3 URI.

    Declaration
    public static string ToAwsS3Uri(string uri)
    Parameters
    Type Name Description
    string uri

    The source URI.

    Returns
    Type Description
    string

    The equivalent S3 URI.

    TryParseIPv4Address(string, out IPAddress)

    Attempts to parse an IPv4 address.

    Declaration
    public static bool TryParseIPv4Address(string input, out IPAddress address)
    Parameters
    Type Name Description
    string input

    The address text.

    IPAddress address

    Set to the parsed address on success.

    Returns
    Type Description
    bool

    true on success.

    TryParseIPv4Endpoint(string, out IPEndPoint)

    Attempts to parse an IPv4 network endpoint.

    Declaration
    public static bool TryParseIPv4Endpoint(string input, out IPEndPoint endpoint)
    Parameters
    Type Name Description
    string input

    The input string.

    IPEndPoint endpoint

    Returns as the parsed endpoint.

    Returns
    Type Description
    bool

    true on success.

    TryParseIPv6Address(string, out IPAddress)

    Attempts to parse an IPv4 address.

    Declaration
    public static bool TryParseIPv6Address(string input, out IPAddress address)
    Parameters
    Type Name Description
    string input

    The address text.

    IPAddress address

    Set to the parsed address on success.

    Returns
    Type Description
    bool

    true on success.

    UintToAddress(uint)

    Converts an unsigned 32-bit integer into an IPv4 address.

    Declaration
    public static IPAddress UintToAddress(uint value)
    Parameters
    Type Name Description
    uint value

    The input value.

    Returns
    Type Description
    IPAddress

    The IPAddress.

    In this article
    Back to top © Copyright 2005-2023 by NEONFORGE LLC