aboutsummaryrefslogtreecommitdiff
path: root/src/wol.rs
blob: 1176b288798333d9a176eb7cab47e170da4f1c9f (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
use std::net::{ToSocketAddrs, UdpSocket};

use tracing::trace;

use crate::error::Error;

/// Creates the magic packet from a mac address
///
/// # Panics
///
/// Panics if `mac_addr` is an invalid mac
pub fn create_buffer(mac_addr: &str) -> Result<Vec<u8>, Error> {
    let mut mac = Vec::new();
    let sp = mac_addr.split(':');
    for f in sp {
        mac.push(u8::from_str_radix(f, 16)?);
    }
    let mut buf = vec![255; 6];
    for _ in 0..16 {
        for i in &mac {
            buf.push(*i);
        }
    }
    Ok(buf)
}

/// Sends a buffer on UDP broadcast
pub fn send_packet<A: ToSocketAddrs>(
    bind_addr: A,
    broadcast_addr: A,
    buffer: &[u8],
) -> Result<usize, Error> {
    let socket = UdpSocket::bind(bind_addr)?;
    socket.set_broadcast(true)?;
    trace!(?buffer ,"start with");
    Ok(socket.send_to(buffer, broadcast_addr)?)
}