Skip to content

Connecting to a router

Daniel Frantík edited this page Oct 18, 2026 · 3 revisions

Connecting to a router

How to open a connection and set its options. Everything in tik4net starts from an ITikConnection, and TikConnectionSetup is the one entry point that creates it: it holds the router coordinates and every option, and opens the transport you name.

using tik4net;

var setup = new TikConnectionSetup("192.168.88.1", "admin", "");

using (ITikConnection connection = setup.Create(TikConnectionType.Api))
{
    Console.WriteLine(connection.CreateCommand("/system/identity/print").ExecuteScalar());
}
  • Build the setup once and keep it — it opens as many connections as you like.
  • Reuse an open connection for many commands; a login costs far more than a command.
  • Dispose it (using) so the socket and the router's login session are released.
  • Switching transport is the TikConnectionType value only — see Connection types & capabilities for which to pick.

Naming the transport

Call Returns Use when
setup.Create(TikConnectionType.Telnet) ITikConnection the transport comes from configuration or a switch
setup.CreateTelnetConnection() ITikCliConnection the transport is fixed in your code

The typed factories return the transport's own interface, so what it can do is checked by the compiler (typed connection interfaces). They are extension methods in the transport's namespace — import it, or IntelliSense will not show them:

Factory Namespace Returns
CreateApiConnection / CreateApiSslConnection tik4net.Api ITikApiConnection
CreateRestConnection / CreateRestSslConnection tik4net.Rest ITikRestConnection
CreateTelnetConnection tik4net.Telnet ITikCliConnection
CreateSshConnection tik4net.Ssh (package tik4net.ssh) ITikCliConnection
CreateWinboxCliConnection tik4net.WinboxCli ITikCliConnection
CreateMacTelnetConnection tik4net.MacTelnet ITikMacCliConnection
CreateWinboxCliMacConnection tik4net.WinboxCliMac ITikMacCliConnection
CreateWinboxNativeConnection tik4net.WinboxNative ITikWinboxNativeConnection
CreateWinboxNativeMacConnection tik4net.WinboxNativeMac ITikWinboxNativeMacConnection
using tik4net;
using tik4net.Api;

using ITikApiConnection connection = new TikConnectionSetup(HOST, USER, PASS).CreateApiConnection();
connection.SafeModeTake();   // a member of ITikApiConnection — no cast, no runtime check
  • Every factory has an …Async twin taking a CancellationToken, as does Create (CreateAsync).
  • setup.CreateUnopened(type) gives you the configured connection without opening it.
  • TikConnectionType.Ssh through setup.Create(…) needs tik4net.Ssh.Tik4NetSsh.Register() once at start-up; CreateSshConnection() does not.

From a connection string

🆕 New in 5.0.

The router, the credentials and the transport can all come from configuration:

var setup = TikConnectionSetup.FromConnectionString(
    "transport=ApiSsl;host=192.168.88.1;user=admin;password=secret;allowInvalidCertificate=true");

using ITikConnection connection = setup.Create();   // the transport the string named
  • ADO.NET syntax: key=value;…, keys case-insensitive, a value holding ; or = is quoted.
  • Keys are the options below, camel-cased (connectTimeout, routerMac, cancellationMode, …), plus transport, host, user, password; timeouts in seconds or as 00:00:15. Exceptions: DebugEnabled is debug; a RoMON agent is romon.host / romon.user / romon.password / romon.port; SshPrivateKey and CertificateValidationCallback have no key — set them on the returned setup.
  • An unknown key, a repeated key or an unreadable value throws — nothing falls back to a default silently.
  • Create(TikConnectionType) on such a setup overrides the string's transport.
  • setup.ToString() writes the setup back with passwords as *** — safe to log.

Where the router is

The first argument is a TikRouterAddress. A plain string converts and is read by its shape:

new TikConnectionSetup("192.168.88.1", "admin", "")                                    // host
new TikConnectionSetup("AA:BB:CC:DD:EE:FF", "admin", "")                               // MAC
new TikConnectionSetup(TikRouterAddress.FromHostAndMac("192.168.88.1", "AA:BB:CC:DD:EE:FF"), "admin", "")
new TikConnectionSetup(TikRouterAddress.FromRomonId("AA:BB:CC:DD:EE:FF"), "admin", "") // behind a RoMON agent
Transports Host MAC
Api, ApiSsl, Rest, RestSsl, Telnet, Ssh, WinboxCli, WinboxNative required not used
MacTelnet, WinboxCliMac, WinboxNativeMac optional (picks the local interface) required when there is no host
  • A missing coordinate is reported at Create, naming what is missing.
  • No IP on the router at all → MAC-layer transports.
  • A router reachable only through another MikroTik → RoMON connection.

Options

Set options as properties of the setup. A transport ignores an option it has no use for, so one setup works for every transport — except SshPrivateKey and RomonAgentSetup, which throw on a transport that cannot honour them rather than log in some other way.

Option Default Applies to
Port the transport's own all
ConnectTimeout 15 s all — connect and login; not MNDP discovery, nor WinBox native's catalog load after login. ≤ 0: no bound of its own — the OS bounds the TCP connect and ReceiveTimeout the login
ReceiveTimeout 30 s all — waiting for a reply
SendTimeout 30 s TCP transports; ignored by Ssh and the MAC-layer ones
Encoding UTF-8 all — change it only for an old RouterOS 6 router that predates UTF-8
DebugEnabled on when a debugger is attached all — see Communication debugging
AllowInvalidCertificate, CertificateValidationCallback false, null ApiSsl, RestSsl — see API connection
SendTagWithSyncCommand true Api, ApiSsl — see Threading
RouterMac from the address, else MNDP MAC-layer transports — see MAC-layer transports
CancellationMode Cooperative CLI transports — see Async and cancellation
CliReadPageSize, CliFieldSeparator per transport CLI transports — see CLI transports
CatalogCachePath %TEMP%\tik4net CLI and WinBox native — menu grammar / .jg catalog cache
ValidateWrites false see Describing menus
SshPrivateKey, SshPrivateKeyPassphrase null Ssh — see SSH connection
RomonAgentSetup null (direct) CLI and WinBox transports — see RoMON connection
var setup = new TikConnectionSetup(HOST, USER, PASS)
{
    ConnectTimeout = TimeSpan.FromSeconds(5),
    ReceiveTimeout = TimeSpan.FromSeconds(60),
};

Opening asynchronously

using ITikConnection connection = await setup.CreateAsync(TikConnectionType.Api, cancellationToken);
  • Api/ApiSsl and Rest/RestSsl can be cancelled anywhere in the open.
  • The CLI transports can be cancelled during the login, not during the TCP connect before it.
  • WinBox native checks the token only before it starts.
  • MNDP discovery on the MAC-layer transports takes up to 5 s of its own; set RouterMac to skip it.

ConnectionFactory

The older entry point, kept for existing code. It builds a TikConnectionSetup internally:

using ITikConnection connection = ConnectionFactory.OpenConnection(TikConnectionType.Api, HOST, USER, PASS);

The host/user/password overloads cannot carry options; OpenConnection(type, setup) can. In new code call setup.Create(type) directly.

Platform notes

  • The packages target netstandard2.0 and net8.0: .NET Framework 4.6.1+, .NET Core / .NET 5+, Xamarin, Unity. The IAsyncEnumerable streaming reads exist on net8.0 only.
  • Trimming and Native AOT: the transports and the low-level / ADO.NET-like APIs (tik4net.dll) are trim- and AOT-safe. The O/R mapper is not — it reads your entity types by reflection, and its methods are marked [RequiresUnreferencedCode], so a trimmed publish warns (IL2026 / IL3050) at each call. Either use the command levels, or root your entity assembly:
<ItemGroup>
  <TrimmerRootAssembly Include="MyApp.Entities" />
</ItemGroup>

See also

Clone this wiki locally