RustForge

rust-kernel

Rustbelt: a hobby x86_64 kernel written in Rust

rust-kernel / user / host.rs
1091 bytes ยท raw
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
//! `host name` (alias `nslookup`): look up a name's IPv4 addresses.
//!
//! DNS turns names into addresses. We send a UDP query to the DNS server
//! DHCP told us about (QEMU's is 10.0.2.3, which forwards to the host's
//! resolver), asking for the name's "A" (IPv4 address) records. smoltcp
//! builds and parses the DNS packets; the kernel's `resolve` syscall wraps
//! it (on Linux, DNS lives in the C library instead).
#![no_std]
#![no_main]

#[macro_use]
#[path = "ulib.rs"]
mod ulib;

fn main() -> i64 {
    let Some(name) = ulib::arg(1) else {
        eprintln!("usage: host name");
        return 2;
    };
    let mut addrs = [[0u8; 4]; 8];
    let n = ulib::resolve_all(name, &mut addrs);
    if n < 0 {
        let why = if n == -ulib::ETIMEDOUT { "no answer from the DNS server" } else { ulib::strerror(n) };
        eprintln!("host: {}: {}", name, why);
        return 1;
    }
    if n == 0 {
        println!("{} has no IPv4 address", name);
        return 1;
    }
    for a in &addrs[..n as usize] {
        println!("{} has address {}", name, ulib::Ip(*a));
    }
    0
}