Getting wet feet with Rust

Since I am quite curious about the Rust programming language I have been playing around with it a bit. Up till now, it is not an easy experience, but I am gettting better at it… I guess.

My first project is to convert my Python driver for the Milight/LimitlessLED light bulbs into Rusty code. And for this I have to start with getting a UDP connection up and running.

With all the example code available this was not a too harsh experience. Still I guess it might be usefull for others to see these examples.

Listening to a udp socket

The code should speak for herselve…

recv.rs

use std::net::{Ipv4Addr, SocketAddrV4, UdpSocket};
use std::io;

fn recv()  -> Result<(), io::Error> {
    // Define the local connection information
    let ip = Ipv4Addr::new(127, 0, 0, 1);
    let connection = SocketAddrV4::new(ip, 9991);

    // Bind the socket
    let socket = try!(UdpSocket::bind(connection));

    // Read from the socket
    let mut buf = [0; 10];
    let (amt, src) = try!(socket.recv_from(&mut buf));

    // Print only the valid data (slice)
    println!("{:?}", &buf[0 .. amt]);

    Ok(())
}

fn main() {
    match recv() {
        Ok(()) => println!("All recv-ing went well"),
        Err(err) => println!("Error: {:?}", err),
    }
}

or see this link.

Sending UDP packets

The code should speak for herselve…

snd.rs

use std::net::{Ipv4Addr, SocketAddrV4, UdpSocket};
use std::io;

fn snd()  -> Result<(), io::Error> {
    // Define the local connection (to send the data from)
    let ip = Ipv4Addr::new(127, 0, 0, 1);
    let connection = SocketAddrV4::new(ip, 9992);

    // Bind the socket
    let socket = try!(UdpSocket::bind(connection));

    // Define the remote connection (to send the data to)
    let connection2 = SocketAddrV4::new(ip, 9991);

    // Send data via the socket
    let buf = &[0x01, 0x02, 0x03];
    try!(socket.send_to(buf, connection2));
    println!("{:?}", buf);

    Ok(())
}

fn main() {
    match snd() {
        Ok(()) => println!("All snd-ing went well"),
        Err(err) => println!("Error: {:?}", err),
    }
}

or see this link.

~ Patrick