trying to remove dhcp lease in C#

Hello ,
I’m tryin to remove dhcp clients by using this all this commands (every time another command…) :

mikrotik.Send("/ip/dhcp-server/lease/remove");
mikrotik.Send("?=server=dhcp1" , true);
mikrotik.Send("?server=dhcp1" , true);
mikrotik.Send("?server=all" , true);
mikrotik.Send("?=server=all" , true);
foreach ?(string m in mikrotik.Read())
{
}

in all of them I get no error - “!done”
but it doesn’t remove nothing …

but when I do this :

mikrotik.Send("=.id=*2" , true);

it remove me the *2 client…


why?
what is wrong?

Thanks ,

You are using a query word in a non-print operation, which is not supported.

https://wiki.mikrotik.com/wiki/Manual:API#Queries

print command > accepts query words that limit set of returned sentences. This feature is available since RouterOS 3.21.

Alternative is to query first and then remove by id:


var ids = new List<string>();

mikrotik.Send("/ip/dhcp-server/lease/print");
mikrotik.Send("?-server", true);

foreach (var h in mikrotik.Read())
{
  var startIndex = h.IndexOf(".id=") + 4;
  if (startIndex >= 4)
  {
    var endIndex = h.IndexOf("=", startIndex);
    var id = h.Substring(startIndex, endIndex - startIndex);
    ids.Add(id);
  }
}

foreach (var id in ids)
{
  mikrotik.Send("/ip/dhcp-server/lease/remove");
  mikrotik.Send("=.id=" + id, true);
  Console.WriteLine(mikrotik.Read());
}

Note that while Winbox shows server=all, the server is actually undefined for these entries (query word -server).

yes ,
this is what I did for now
saved all the Id and then remove them 1 by 1

Thanks ,

The Tik4Net (strong-typed entity) example:

https://github.com/danikf/tik4net


using tik4net;
using tik4net.Objects;
using tik4net.Objects.Ip.DhcpServer;

var host = "192.168.88.1";
var user = "admin";
var pass = "password";

using (var conn = tik4net.ConnectionFactory.OpenConnection(TikConnectionType.Api, host, user, pass))
{
  var filter = conn.CreateParameter("-server", "");
  var leases = conn.LoadList<DhcpServerLease>(filter);

  foreach (var lease in leases)
  {
    conn.Delete(lease);
  }
}

all my code is in the mikrotik API and not the Tik4Net
I wnat to start working with this - when I have time
:slight_smile:

Thanks ,

You have wasted a lot of time already. Just pointing out there are better and quicker solutions.

Assuming you have never installed a NuGet package?