summaryrefslogtreecommitdiffstats
path: root/third_party/rust/dns-parser/examples/sync_tcp_client.rs
blob: 732e8d3bfbaf62bbd2acc0fb115ff37805d84586 (plain)
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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
extern crate dns_parser;

use std::env;
use std::error::Error;
use std::io::{Read, Write};
use std::net::TcpStream;
use std::process;


use dns_parser::{Builder, Packet, RData, ResponseCode};
use dns_parser::rdata::a::Record;
use dns_parser::{QueryType, QueryClass};


fn main() {
    let mut code = 0;
    for name in env::args().skip(1) {
        match resolve(&name) {
            Ok(()) => {},
            Err(e) => {
                eprintln!("Error resolving {:?}: {}", name, e);
                code = 1;
            }
        }
    }
    process::exit(code);
}

fn resolve(name: &str) -> Result<(), Box<Error>> {
    let mut conn = TcpStream::connect("127.0.0.1:53")?;
    let mut builder = Builder::new_query(1, true);
    builder.add_question(name, false, QueryType::A, QueryClass::IN);
    let packet = builder.build().map_err(|_| "truncated packet")?;
    let psize = [((packet.len() >> 8) & 0xFF) as u8,
                 (packet.len() & 0xFF) as u8];
    conn.write_all(&psize[..])?;
    conn.write_all(&packet)?;
    let mut buf = vec![0u8; 4096];
    let mut off = 0;
    let pkt = loop {
        if buf.len() - off < 4096 {
            buf.extend(&[0u8; 4096][..]);
        }
        match conn.read(&mut buf[off..]) {
            Ok(num) => {
                off += num;
                if off < 2 { continue; }
                let bytes = ((buf[0] as usize) << 8) | buf[1] as usize;
                if off < bytes + 2 {
                    continue;
                }
                if num == 0 {
                    return Err("Partial packet received".into());
                }
                break Packet::parse(&buf[2..off])?;
            }
            Err(e) => {
                return Err(Box::new(e));
            }
        }
    };
    if pkt.header.response_code != ResponseCode::NoError {
        return Err(pkt.header.response_code.into());
    }
    if pkt.answers.len() == 0 {
        return Err("No records received".into());
    }
    for ans in pkt.answers {
        match ans.data {
            RData::A(Record(ip)) => {
                println!("{}", ip);
            }
            _ => {} // ignore
        }
    }
    Ok(())
}