simple_mdns/
conversion_utils.rs

1//! Provides helper functions to convert net addresses to resource records
2
3use simple_dns::{
4    rdata::{RData, A, AAAA, SRV, TXT},
5    Name, ResourceRecord, CLASS,
6};
7use std::{collections::HashMap, convert::TryFrom, net::IpAddr};
8use std::{convert::From, net::SocketAddr};
9
10/// Convert the addr to an A (IpV4) or AAAA (IpV6) record
11pub fn ip_addr_to_resource_record<'a>(
12    name: &Name<'a>,
13    addr: IpAddr,
14    rr_ttl: u32,
15) -> ResourceRecord<'a> {
16    match addr {
17        IpAddr::V4(ip) => {
18            ResourceRecord::new(name.clone(), CLASS::IN, rr_ttl, RData::A(A::from(ip)))
19        }
20        IpAddr::V6(ip) => {
21            ResourceRecord::new(name.clone(), CLASS::IN, rr_ttl, RData::AAAA(AAAA::from(ip)))
22        }
23    }
24}
25
26/// Convert the port to an SRV record. The provided name will be used as resource name and target
27pub fn port_to_srv_record<'a>(name: &Name<'a>, port: u16, rr_ttl: u32) -> ResourceRecord<'a> {
28    ResourceRecord::new(
29        name.clone(),
30        CLASS::IN,
31        rr_ttl,
32        RData::SRV(SRV {
33            port,
34            priority: 0,
35            target: name.clone(),
36            weight: 0,
37        }),
38    )
39}
40
41/// Convert the socket address to a SRV and an A (IpV4) or AAAA (IpV6) record, the return will be a tuple where the SRV is the first item
42pub fn socket_addr_to_srv_and_address<'a>(
43    name: &Name<'a>,
44    addr: SocketAddr,
45    rr_ttl: u32,
46) -> (ResourceRecord<'a>, ResourceRecord<'a>) {
47    (
48        port_to_srv_record(name, addr.port(), rr_ttl),
49        ip_addr_to_resource_record(name, addr.ip(), rr_ttl),
50    )
51}
52
53/// Converts the hashmap to a TXT Record
54pub fn hashmap_to_txt<'a>(
55    name: &Name<'a>,
56    attributes: HashMap<String, Option<String>>,
57    rr_ttl: u32,
58) -> Result<ResourceRecord<'a>, crate::SimpleMdnsError> {
59    let txt = TXT::try_from(attributes)?;
60
61    Ok(ResourceRecord::new(
62        name.clone(),
63        CLASS::IN,
64        rr_ttl,
65        RData::TXT(txt),
66    ))
67}