Skip to main content
Redhat Developers  Logo
  • AI

    Get started with AI

    • Red Hat AI
      Accelerate the development and deployment of enterprise AI solutions.
    • AI learning hub
      Explore learning materials and tools, organized by task.
    • AI interactive demos
      Click through scenarios with Red Hat AI, including training LLMs and more.
    • AI/ML learning paths
      Expand your OpenShift AI knowledge using these learning resources.
    • AI quickstarts
      Focused AI use cases designed for fast deployment on Red Hat AI platforms.
    • No-cost AI training
      Foundational Red Hat AI training.

    Featured resources

    • OpenShift AI learning
    • Open source AI for developers
    • AI product application development
    • Open source-powered AI/ML for hybrid cloud
    • AI and Node.js cheat sheet

    Red Hat AI Factory with NVIDIA

    • Red Hat AI Factory with NVIDIA is a co-engineered, enterprise-grade AI solution for building, deploying, and managing AI at scale across hybrid cloud environments.
    • Explore the solution
  • Learn

    Self-guided

    • Documentation
      Find answers, get step-by-step guidance, and learn how to use Red Hat products.
    • Learning paths
      Explore curated walkthroughs for common development tasks.
    • Guided learning
      Receive custom learning paths powered by our AI assistant.
    • See all learning

    Hands-on

    • Developer Sandbox
      Spin up Red Hat's products and technologies without setup or configuration.
    • Interactive labs
      Learn by doing in these hands-on, browser-based experiences.
    • Interactive demos
      Click through product features in these guided tours.

    Browse by topic

    • AI/ML
    • Automation
    • Java
    • Kubernetes
    • Linux
    • See all topics

    Training & certifications

    • Courses and exams
    • Certifications
    • Skills assessments
    • Red Hat Academy
    • Learning subscription
    • Explore training
  • Build

    Get started

    • Red Hat build of Podman Desktop
      A downloadable, local development hub to experiment with our products and builds.
    • Developer Sandbox
      Spin up Red Hat's products and technologies without setup or configuration.

    Download products

    • Access product downloads to start building and testing right away.
    • Red Hat Enterprise Linux
    • Red Hat AI
    • Red Hat OpenShift
    • Red Hat Ansible Automation Platform
    • See all products

    Featured

    • Red Hat build of OpenJDK
    • Red Hat JBoss Enterprise Application Platform
    • Red Hat OpenShift Dev Spaces
    • Red Hat Developer Toolset

    References

    • E-books
    • Documentation
    • Cheat sheets
    • Architecture center
  • Community

    Get involved

    • Events
    • Live AI events
    • Red Hat Summit
    • Red Hat Accelerators
    • Community discussions

    Follow along

    • Articles & blogs
    • Developer newsletter
    • Videos
    • Github

    Get help

    • Customer service
    • Customer support
    • Regional contacts
    • Find a partner

    Join the Red Hat Developer program

    • Download Red Hat products and project builds, access support documentation, learning content, and more.
    • Explore the benefits

Connecting .NET Core to D-Bus

<p>&nbsp;</p> <quillbot-extension-portal></quillbot-extension-portal>

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

    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

    • Red Hat Hardened Images: Top 5 benefits for software developers

    • How EvalHub manages two-layer Kubernetes control planes

    • Tekton joins the CNCF as an incubating project

    • Federated identity across the hybrid cloud using zero trust workload identity manager

    • Confidential virtual machine storage attack scenarios

    Red Hat Developers logo LinkedIn YouTube Twitter Facebook

    Platforms

    • Red Hat AI
    • Red Hat Enterprise Linux
    • Red Hat OpenShift
    • Red Hat Ansible Automation Platform
    • See all products

    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
    © 2026 Red Hat

    Red Hat legal and privacy links

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

    Chat Support

    Please log in with your Red Hat account to access chat support.