#mdns #bonjour #avahi #dnssd #api-bindings

zeroconf

跨平台库,封装了 ZeroConf/mDNS 实现,如 Bonjour 或 Avahi

30 个版本

0.15.0 2024 年 8 月 10 日
0.14.2 2024 年 7 月 26 日
0.14.1 2024 年 1 月 29 日
0.12.0 2023 年 9 月 23 日
0.6.2 2020 年 9 月 29 日

#190网络编程

Download history 690/week @ 2024-04-30 233/week @ 2024-05-07 263/week @ 2024-05-14 503/week @ 2024-05-21 546/week @ 2024-05-28 367/week @ 2024-06-04 264/week @ 2024-06-11 378/week @ 2024-06-18 1466/week @ 2024-06-25 1266/week @ 2024-07-02 941/week @ 2024-07-09 1338/week @ 2024-07-16 1059/week @ 2024-07-23 2091/week @ 2024-07-30 1629/week @ 2024-08-06 791/week @ 2024-08-13

每月下载量 5,732
7 crates 中使用

自定义许可证

160KB
3.5K SLoC

zeroconf

zeroconf 是一个跨平台库,封装了底层的 ZeroConf/mDNS 实现,如 BonjourAvahi,提供了一种简单且符合习惯的方式来注册和浏览服务。

先决条件

在 Linux 上

$ sudo apt install xorg-dev libxcb-shape0-dev libxcb-xfixes0-dev clang avahi-daemon libavahi-client-dev

在 Windows 上

Bonjour 必须已安装。它包含在 iTunesBonjour 打印服务 中。有关进一步的分发和捆绑详情,请参阅 Apple 开发者网站

示例

注册服务

在注册服务时,您可以可选地传递一个 "上下文" 来通过回调传递状态。唯一的要求是这个上下文实现了 Any 特性,大多数类型都会自动实现。有关上下文的更多信息,请参阅 MdnsService

#[macro_use]
extern crate log;

use clap::Parser;

use std::any::Any;
use std::sync::{Arc, Mutex};
use std::time::Duration;
use zeroconf::prelude::*;
use zeroconf::{MdnsService, ServiceRegistration, ServiceType, TxtRecord};

#[derive(Parser, Debug)]
#[command(author, version, about)]
struct Args {
    /// Name of the service type to register
    #[clap(short, long, default_value = "http")]
    name: String,

    /// Protocol of the service type to register
    #[clap(short, long, default_value = "tcp")]
    protocol: String,

    /// Sub-types of the service type to register
    #[clap(short, long)]
    sub_types: Vec<String>,
}

#[derive(Default, Debug)]
pub struct Context {
    service_name: String,
}

fn main() -> zeroconf::Result<()> {
    env_logger::init();

    let Args {
        name,
        protocol,
        sub_types,
    } = Args::parse();

    let sub_types = sub_types.iter().map(|s| s.as_str()).collect::<Vec<_>>();
    let service_type = ServiceType::with_sub_types(&name, &protocol, sub_types)?;
    let mut service = MdnsService::new(service_type, 8080);
    let mut txt_record = TxtRecord::new();
    let context: Arc<Mutex<Context>> = Arc::default();

    txt_record.insert("foo", "bar")?;

    service.set_name("zeroconf_example_service");
    service.set_registered_callback(Box::new(on_service_registered));
    service.set_context(Box::new(context));
    service.set_txt_record(txt_record);

    let event_loop = service.register()?;

    loop {
        // calling `poll()` will keep this service alive
        event_loop.poll(Duration::from_secs(0))?;
    }
}

fn on_service_registered(
    result: zeroconf::Result<ServiceRegistration>,
    context: Option<Arc<dyn Any>>,
) {
    let service = result.expect("failed to register service");

    info!("Service registered: {:?}", service);

    let context = context
        .as_ref()
        .expect("could not get context")
        .downcast_ref::<Arc<Mutex<Context>>>()
        .expect("error down-casting context")
        .clone();

    context
        .lock()
        .expect("failed to obtain context lock")
        .service_name = service.name().clone();

    info!("Context: {:?}", context);

    // ...
}

浏览服务

#[macro_use]
extern crate log;

use clap::Parser;

use std::any::Any;
use std::sync::Arc;
use std::time::Duration;
use zeroconf::prelude::*;
use zeroconf::{MdnsBrowser, ServiceDiscovery, ServiceType};

/// Example of a simple mDNS browser
#[derive(Parser, Debug)]
#[command(author, version, about)]
struct Args {
    /// Name of the service type to browse
    #[clap(short, long, default_value = "http")]
    name: String,

    /// Protocol of the service type to browse
    #[clap(short, long, default_value = "tcp")]
    protocol: String,

    /// Sub-type of the service type to browse
    #[clap(short, long)]
    sub_type: Option<String>,
}

fn main() -> zeroconf::Result<()> {
    env_logger::init();

    let Args {
        name,
        protocol,
        sub_type,
    } = Args::parse();

    let sub_types: Vec<&str> = match sub_type.as_ref() {
        Some(sub_type) => vec![sub_type],
        None => vec![],
    };

    let service_type =
        ServiceType::with_sub_types(&name, &protocol, sub_types).expect("invalid service type");

    let mut browser = MdnsBrowser::new(service_type);

    browser.set_service_discovered_callback(Box::new(on_service_discovered));

    let event_loop = browser.browse_services()?;

    loop {
        // calling `poll()` will keep this browser alive
        event_loop.poll(Duration::from_secs(0))?;
    }
}

fn on_service_discovered(
    result: zeroconf::Result<ServiceDiscovery>,
    _context: Option<Arc<dyn Any>>,
) {
    info!(
        "Service discovered: {:?}",
        result.expect("service discovery failed")
    );

    // ...
}

资源

依赖项

~1–3.5MB
~70K SLoC