Skip to main content
Redhat Developers  Logo
  • Products

    Platforms

    • Red Hat Enterprise Linux
      Red Hat Enterprise Linux Icon
    • Red Hat AI
      Red Hat AI
    • Red Hat OpenShift
      Openshift icon
    • Red Hat Ansible Automation Platform
      Ansible icon
    • View All Red Hat Products

    Featured

    • Red Hat build of OpenJDK
    • Red Hat Developer Hub
    • Red Hat JBoss Enterprise Application Platform
    • Red Hat OpenShift Dev Spaces
    • Red Hat OpenShift Local
    • Red Hat Developer Sandbox

      Try Red Hat products and technologies without setup or configuration fees for 30 days with this shared Openshift and Kubernetes cluster.
    • Try at no cost
  • Technologies

    Featured

    • AI/ML
      AI/ML Icon
    • Linux
      Linux Icon
    • Kubernetes
      Cloud icon
    • Automation
      Automation Icon showing arrows moving in a circle around a gear
    • View All Technologies
    • Programming Languages & Frameworks

      • Java
      • Python
      • JavaScript
    • System Design & Architecture

      • Red Hat architecture and design patterns
      • Microservices
      • Event-Driven Architecture
      • Databases
    • Developer Productivity

      • Developer productivity
      • Developer Tools
      • GitOps
    • Automated Data Processing

      • AI/ML
      • Data Science
      • Apache Kafka on Kubernetes
    • Platform Engineering

      • DevOps
      • DevSecOps
      • Ansible automation for applications and services
    • Secure Development & Architectures

      • Security
      • Secure coding
  • Learn

    Featured

    • Kubernetes & Cloud Native
      Openshift icon
    • Linux
      Rhel icon
    • Automation
      Ansible cloud icon
    • AI/ML
      AI/ML Icon
    • View All Learning Resources

    E-Books

    • GitOps Cookbook
    • Podman in Action
    • Kubernetes Operators
    • The Path to GitOps
    • View All E-books

    Cheat Sheets

    • Linux Commands
    • Bash Commands
    • Git
    • systemd Commands
    • View All Cheat Sheets

    Documentation

    • Product Documentation
    • API Catalog
    • Legacy Documentation
  • Developer Sandbox

    Developer Sandbox

    • Access Red Hat’s products and technologies without setup or configuration, and start developing quicker than ever before with our new, no-cost sandbox environments.
    • Explore Developer Sandbox

    Featured Developer Sandbox activities

    • Get started with your Developer Sandbox
    • OpenShift virtualization and application modernization using the Developer Sandbox
    • Explore all Developer Sandbox activities

    Ready to start developing apps?

    • Try at no cost
  • Blog
  • Events
  • Videos

Connecting .NET Core to D-Bus

 

September 18, 2017
Tom Deseyn
Related topics:
.NET
Related products:
Developer Tools

Share:

    D-Bus is a Linux message bus system. Many system daemons (like systemd, PulseAudio, bluez) and desktop services can be controlled via D-Bus. Some applications can be reached via the global system bus and others are on a per-user-login-session bus.

    Higher-level bindings are available for various popular frameworks and languages. Tmds.DBus is a .NET implementation. The library is based on dbus-sharp/ndesk-dbus, which target Mono/.NET 2.0. Tmds.DBus leverages async/await (Task-based asynchronous pattern) introduced in .NET 4.5/C# 5.0. The library targets netstandard1.5 which means it runs on .NET 4.6.1+ and .NET Core 1.0+.

    To use a D-Bus service, its functionality must be described as C# interfaces. Because this is a tedious and error-prone task, Tmds.DBus comes with a cli tool that does this for us. The tool queries the services and automatically generates the interface code. .NET Core 2.0 is needed as a development dependency to run the tool.

    If you don't have .NET Core on your machine, you can find installation instructions at www.dot.net/core. Alternatively, on Fedora, you can install the DotNet SIG packages.

    In this post, we will build a small application that writes a console message when a network interface changes state. To detect the state changes we use the NetworkManager daemon’s D-Bus service. We will perform the steps of code-generation and then enhance the generated code.

    We start by using the dotnet cli to create a new console application:

    $ dotnet new console -o netmon
    $ cd netmon

    Now we add references to Tmds.DBus and Tmds.DBus.Tool in netmon.csproj. We also set the LangVersion so we can use an async Main (C# 7.1).

    <Project Sdk="Microsoft.NET.Sdk">
      <PropertyGroup>
        <OutputType>Exe</OutputType>
        <TargetFramework>netcoreapp2.0</TargetFramework>
        <LangVersion>7.1</LangVersion>
      </PropertyGroup>
      <ItemGroup>
        <PackageReference Include="Tmds.DBus" Version="0.5.0" />
        <DotNetCliToolReference Include="Tmds.DBus.Tool" Version="0.5.0" />
      </ItemGroup>
    </Project>

    Now we restore to fetch these dependencies:

    $ dotnet restore

    Next, we use the list command to find out some information about the NetworkManager service. list services show the available services. Using list objects we can see the objects exposed by a service. The command prints the path of each object followed by the interfaces it implements.

    $ dotnet dbus list services --bus system | grep NetworkManager
    org.freedesktop.NetworkManager
    $ dotnet dbus list objects --bus system --service org.freedesktop.NetworkManager | head -2
    /org/freedesktop : org.freedesktop.DBus.ObjectManager
    /org/freedesktop/NetworkManager : org.freedesktop.NetworkManager

    The output of the commands show us the org.freedesktop.NetworkManager service is on the system bus and has an entry point object at /org/freedesktop/NetworkManager which implements org.freedesktop.NetworkManager.

    Now we invoke the codegen command to generate C# interfaces for the NetworkManager service.

    $ dotnet dbus codegen --bus system --service org.freedesktop.NetworkManager

    This generates a NetworkManager.DBus.cs file in the local folder.

    We update Program.cs to use an async Main and instantiate an INetworkManager proxy object. This proxy is created on Connection.System. This singleton makes it easy to share the same Connection throughout the application.

    using System;
    using Tmds.DBus;
    using NetworkManager.DBus;
    using System.Threading.Tasks;
    namespace DBusExample
    {
      class Program
      {
        static async Task Main(string[] args)
        {
          Console.WriteLine("Monitoring network state changes. Press Ctrl-C to stop.");
          var systemConnection = Connection.System;
          var networkManager = systemConnection.CreateProxy<INetworkManager>("org.freedesktop.NetworkManager", "/org/freedesktop/NetworkManager");
          // TODO: watch state changes
          await Task.Delay(int.MaxValue);
        }
      }
    }

    When we look at the INetworkManager interface in NetworkManager.DBus.cs, we see it has a GetDevicesAsync method.

    Task<ObjectPath[]> GetDevicesAsync();

    This method is returning ObjectPath[]. These paths refer to other objects of the D-Bus service. We can use them with CreateProxy passing the IDevice type. But instead, we'll update the method to reflect it is returning IDevice objects.

    Task<IDevice[]> GetDevicesAsync();

    Now we can add the code to iterate over the devices and add a signal handler for the state change:

    foreach (var device in await networkManager.GetDevicesAsync())
    {
      var interfaceName = await device.GetInterfaceAsync();
      await device.WatchStateChangedAsync(
      change => Console.WriteLine($"{interfaceName}: {change.oldState} -> {change.newState}"));
    }

    When we run our program and change our network interfaces (e.g. turn on/off WiFi) notifications show up:

    $ dotnet run
    Press any key to close the application.
    wlp4s0: 100 -> 20

    If we look up the documentation of the StateChanged signal, we find the meaning of the magical constants: NMDeviceState.

    We can model this enumeration in C#:

    enum DeviceState : uint
    {
      Unknown = 0,
      Unmanaged = 10,
      Unavailable = 20,
      Disconnected = 30,
      Prepare = 40,
      Config = 50,
      NeedAuth = 60,
      IpConfig = 70,
      IpCheck = 80,
      Secondaries = 90,
      Activated = 100,
      Deactivating = 110,
      Failed = 120
    }

    We add the enum to NetworkManager.DBus.cs and then update the signature of WatchStateChangedAsync so it uses DeviceState instead of uint.

    Task<IDisposable> WatchStateChangedAsync(Action<(DeviceState newState, DeviceState oldState, uint reason)> action);

    When we run our application again, we see more meaningful messages:

    $ dotnet run
    Press any key to close the application.
    wlp4s0: Activated -> Unavailable

    That finishes the example. We've covered the basic usage of Tmds.DBus and Tmds.DBus.Tool. To learn more about Tmds.DBus and D-Bus, check out the GitHub project and freedesktop.org website.

    Last updated: February 6, 2024

    Recent Posts

    • Why some agentic AI developers are moving code from Python to Rust

    • Confidential VMs: The core of confidential containers

    • Benchmarking with GuideLLM in air-gapped OpenShift clusters

    • Run Qwen3-Next on vLLM with Red Hat AI: A step-by-step guide

    • How to implement observability with Python and Llama Stack

    Red Hat Developers logo LinkedIn YouTube Twitter Facebook

    Products

    • Red Hat Enterprise Linux
    • Red Hat OpenShift
    • Red Hat Ansible Automation Platform

    Build

    • Developer Sandbox
    • Developer Tools
    • Interactive Tutorials
    • API Catalog

    Quicklinks

    • Learning Resources
    • E-books
    • Cheat Sheets
    • Blog
    • Events
    • Newsletter

    Communicate

    • About us
    • Contact sales
    • Find a partner
    • Report a website issue
    • Site Status Dashboard
    • Report a security problem

    RED HAT DEVELOPER

    Build here. Go anywhere.

    We serve the builders. The problem solvers who create careers with code.

    Join us if you’re a developer, software engineer, web designer, front-end designer, UX designer, computer scientist, architect, tester, product manager, project manager or team lead.

    Sign me up

    Red Hat legal and privacy links

    • About Red Hat
    • Jobs
    • Events
    • Locations
    • Contact Red Hat
    • Red Hat Blog
    • Inclusion at Red Hat
    • Cool Stuff Store
    • Red Hat Summit
    © 2025 Red Hat

    Red Hat legal and privacy links

    • Privacy statement
    • Terms of use
    • All policies and guidelines
    • Digital accessibility

    Report a website issue