whoizz 0.1.0

Tiny, dependency-light RFC 3912 whois client with best-effort field extraction
Documentation
use std::io::{Read, Write};
use std::net::{TcpStream, ToSocketAddrs};
use std::time::Duration;

use crate::WhoisError;

/// RFC 3912 whois default port.
pub(crate) const WHOIS_PORT: u16 = 43;

/// Send a whois query over TCP. Blocks until the server closes the
/// connection or the timeout elapses. Returns the raw response body.
pub(crate) fn query(
    host: &str,
    port: u16,
    query: &str,
    timeout: Duration,
) -> Result<String, WhoisError> {
    let addr = (host, port)
        .to_socket_addrs()?
        .next()
        .ok_or_else(|| WhoisError::NoAddress(host.to_string()))?;

    let mut stream = TcpStream::connect_timeout(&addr, timeout)?;
    stream.set_read_timeout(Some(timeout))?;
    stream.set_write_timeout(Some(timeout))?;

    // RFC 3912: query followed by CRLF.
    stream.write_all(query.as_bytes())?;
    stream.write_all(b"\r\n")?;
    stream.flush()?;

    let mut buf = String::with_capacity(4096);
    stream.read_to_string(&mut buf)?;
    Ok(buf)
}