Skip to content

Instantly share code, notes, and snippets.

@gkbrk gkbrk/whois.rs
Created Dec 5, 2015

Embed
What would you like to do?
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
You can’t perform that action at this time.