Added examples

This commit is contained in:
pradt2
2022-08-22 20:54:03 +01:00
parent 3d2705fc23
commit aa857f8230
2 changed files with 66 additions and 0 deletions

35
examples/read.rs Normal file
View File

@@ -0,0 +1,35 @@
use stun_proto::*;
/**
In this example, we are reading an example
BindingRequest with a ChangeRequest attribute.
*/
fn main() {
let req = [
0x00, 0x01, // type: Binding Request
0x00, 0x08, // length: 8 (header does not count)
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x01, // transaction id: 1 (16 bytes total)
0x00, 0x03, // attribute type: Change Request
0x00, 0x04, // attribute length: 4
0x00, 0x00, 0x00, 0x60, // request to change both the IP and port
];
let reader = rfc3489::Reader::new(&req);
let msg_type = reader.get_message_type().unwrap();
assert_eq!(rfc3489::MessageType::BindingRequest, msg_type);
let transaction_id = reader.get_transaction_id().unwrap();
assert_eq!(1u128, transaction_id);
let attr = reader.get_attributes().next().unwrap().unwrap();
if let rfc3489::ReaderAttribute::ChangeRequest(change_request) = attr {
assert_eq!(true, change_request.get_change_ip().unwrap());
assert_eq!(true, change_request.get_change_port().unwrap());
}
}

31
examples/write.rs Normal file
View File

@@ -0,0 +1,31 @@
use stun_proto::*;
/**
In this example, we are creating the same attribute
that is used in the read.rs example.
*/
fn main() {
let mut buf = [0u8; 28];
let mut writer = rfc3489::Writer::new(&mut buf);
writer.set_message_type(rfc3489::MessageType::BindingRequest).unwrap();
writer.set_transaction_id(1).unwrap();
writer.add_attr(rfc3489::WriterAttribute::ChangeRequest {change_ip: true, change_port: true}).unwrap();
let bytes_used = writer.finish().unwrap();
// this is the same attribute as in the read.rs example
let req = [
0x00, 0x01, // type: Binding Request
0x00, 0x08, // length: 8 (header does not count)
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x01, // transaction id: 1 (16 bytes total)
0x00, 0x03, // attribute type: Change Request
0x00, 0x04, // attribute length: 4
0x00, 0x00, 0x00, 0x60, // request to change both the IP and port
];
assert_eq!(buf.len(), bytes_used as usize);
assert_eq!(req, buf);
}