Module stun_types::message

source ·
Expand description

STUN Messages

Provides types for generating, parsing, and manipulating STUN messages as specified in one of RFC8489, RFC5389, or RFC3489.

§Examples

§Parse a STUN Message

use stun_types::prelude::*;
use stun_types::attribute::{RawAttribute, PasswordAlgorithm, PasswordAlgorithmValue};
use stun_types::message::{Message, MessageType, MessageClass, BINDING};

let msg_data = [
    0x00, 0x01, 0x00, 0x08, // method, class and length
    0x21, 0x12, 0xA4, 0x42, // Fixed STUN magic bytes
    0x00, 0x00, 0x00, 0x00, // \
    0x00, 0x00, 0x00, 0x00, // } transaction ID
    0x00, 0x00, 0x73, 0x92, // /
    0x00, 0x1D, 0x00, 0x04, // PasswordAlgorithm ttribute
    0x00, 0x02, 0x00, 0x00 // PasswordAlgorithm attribute
];
let msg = Message::from_bytes(&msg_data).unwrap();

// the various parts of a message can be retreived
assert_eq!(msg.get_type(), MessageType::from_class_method(MessageClass::Request, BINDING));
assert_eq!(msg.transaction_id(), 0x7392.into());

// Attributes can be retrieved as raw values.
let msg_attr = msg.raw_attribute(0x1D.into()).unwrap();
let attr = RawAttribute::new(0x1D.into(), &[0, 2, 0, 0]);
assert_eq!(msg_attr, attr);

// Or as typed values
let attr = msg.attribute::<PasswordAlgorithm>().unwrap();
assert_eq!(attr.algorithm(), PasswordAlgorithmValue::SHA256);

§Generating a Message

use stun_types::prelude::*;
use stun_types::attribute::Software;
use stun_types::message::{Message, BINDING};

// Automatically generates a transaction ID.
let mut msg = Message::builder_request(BINDING);

let software_name = "stun-types";
let software = Software::new(software_name).unwrap();
assert_eq!(software.software(), software_name);
msg.add_attribute(&software).unwrap();

let attribute_data = [
    0x80, 0x22, 0x00, 0x0a, // attribute type (0x8022) and length (0x000a)
    0x73, 0x74, 0x75, 0x6E, // s t u n
    0x2D, 0x74, 0x79, 0x70, // - t y p
    0x65, 0x73, 0x00, 0x00  // e s
];

let msg_data = msg.build();
// ignores the randomly generated transaction id
assert_eq!(msg_data[20..], attribute_data);

Structs§

Enums§

Constants§

  • The value of the binding message type. Can be used in either a request or an indication message.
  • The value of magic cookie (in network byte order) as specified in RFC5389, and RFC8489.