use std::io::{Read, Write};
use std::net::{TcpStream, ToSocketAddrs};
use std::time::Duration;
use crate::WhoisError;
pub(crate) const WHOIS_PORT: u16 = 43;
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))?;
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)
}