Skip to content

Instantly share code, notes, and snippets.

@gkbrk
Created December 5, 2015 17:43
Show Gist options
  • Star 10 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gkbrk/0c2317e9f72dbe55695b to your computer and use it in GitHub Desktop.
Save gkbrk/0c2317e9f72dbe55695b to your computer and use it in GitHub Desktop.
Rust whois client
use std::io::prelude::*;
use std::net::TcpStream;
use std::io::BufReader;
use std::env;
fn get_tld_server(tld: &str) -> Option<String> {
let mut stream = TcpStream::connect("whois.iana.org:43").unwrap();
stream.write_all(format!("{}\n", tld).as_bytes()).unwrap(); //Send the tld
let reader = BufReader::new(stream);
for line in reader.lines() {
let line = line.unwrap();
let parts: Vec<String> = line.splitn(2, ":").map(|x| x.to_string()).collect();
if parts.len() == 2 {
if parts[0].to_lowercase() == "whois" {
return Some(parts[1].trim().to_string());
}
}
}
return None;
}
fn get_whois_data(domain: &str) -> Vec<String> {
let mut next_server: Option<String> = None;
let mut whois_data = Vec::new();
let domain = domain.to_string();
let tld = domain.split(".").last().unwrap(); // Get the top-level domain
let tld_server = match get_tld_server(tld) {
Some(server) => server,
None => {
whois_data.push(format!("Can't find a whois server for {}", domain));
return whois_data;
}
};
let mut stream = TcpStream::connect((&tld_server[..], 43)).unwrap();
stream.write_all(format!("{}\n", domain).as_bytes()).unwrap();
let reader = BufReader::new(stream);
for line in reader.lines() {
let line = line.unwrap();
let parts: Vec<String> = line.splitn(2, ":").map(|x| x.to_string()).collect();
if parts.len() == 2 {
if parts[0].to_lowercase().trim() == "whois server" && !parts[1].trim().is_empty() {
next_server = Some(parts[1].trim().to_owned());
}
}
whois_data.push(line);
}
match next_server {
Some(server) => {
let mut stream = TcpStream::connect((&server[..], 43)).unwrap();
stream.write_all(format!("{}\n", domain).as_bytes()).unwrap();
let reader = BufReader::new(stream);
for line in reader.lines() {
let line = line.unwrap();
whois_data.push(line);
}
},
None => {}
}
return whois_data;
}
fn main() {
let domain = match env::args().nth(1) {
Some(domain) => domain,
None => {
println!("Please enter a domain");
return;
}
};
for line in get_whois_data(&domain).iter() {
println!("{}", line);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment