Update examples with modernized code

This commit is contained in:
Emil Hernvall
2020-06-18 01:47:09 +02:00
parent 31369696d9
commit f815075ae4
10 changed files with 708 additions and 627 deletions

View File

@@ -164,9 +164,7 @@ impl BytePacketBuffer {
}
fn write_qname(&mut self, qname: &str) -> Result<()> {
let split_str = qname.split('.').collect::<Vec<&str>>();
for label in split_str {
for label in qname.split('.') {
let len = label.len();
if len > 0x34 {
return Err("Single label exceeds 63 characters of length".into());
@@ -521,12 +519,18 @@ impl DnsPacket {
}
fn main() -> Result<()> {
let qname = "www.yahoo.com";
// Perform an A query for google.com
let qname = "google.com";
let qtype = QueryType::A;
// Using googles public DNS server
let server = ("8.8.8.8", 53);
// Bind a UDP socket to an arbitrary port
let socket = UdpSocket::bind(("0.0.0.0", 43210))?;
// Build our query packet. It's important that we remember to set the
// `recursion_desired` flag. As noted earlier, the packet id is arbitrary.
let mut packet = DnsPacket::new();
packet.header.id = 6666;
@@ -536,27 +540,34 @@ fn main() -> Result<()> {
.questions
.push(DnsQuestion::new(qname.to_string(), qtype));
// Use our new write method to write the packet to a buffer...
let mut req_buffer = BytePacketBuffer::new();
packet.write(&mut req_buffer)?;
// ...and send it off to the server using our socket:
socket.send_to(&req_buffer.buf[0..req_buffer.pos], server)?;
// To prepare for receiving the response, we'll create a new `BytePacketBuffer`,
// and ask the socket to write the response directly into our buffer.
let mut res_buffer = BytePacketBuffer::new();
socket.recv_from(&mut res_buffer.buf)?;
// As per the previous section, `DnsPacket::from_buffer()` is then used to
// actually parse the packet after which we can print the response.
let res_packet = DnsPacket::from_buffer(&mut res_buffer)?;
println!("{:?}", res_packet.header);
println!("{:#?}", res_packet.header);
for q in res_packet.questions {
println!("{:?}", q);
println!("{:#?}", q);
}
for rec in res_packet.answers {
println!("{:?}", rec);
println!("{:#?}", rec);
}
for rec in res_packet.authorities {
println!("{:?}", rec);
println!("{:#?}", rec);
}
for rec in res_packet.resources {
println!("{:?}", rec);
println!("{:#?}", rec);
}
Ok(())