Skip to content

Instantly share code, notes, and snippets.

@paulohrpinheiro
Created January 15, 2017 17:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save paulohrpinheiro/2619ce23136a71fd4cda5180320f393f to your computer and use it in GitHub Desktop.
Save paulohrpinheiro/2619ce23136a71fd4cda5180320f393f to your computer and use it in GitHub Desktop.
Arquivos para o texto # Rust Pills - resolvendo nomes por DNS
[package]
name = "resolver"
version = "0.1.0"
authors = ["Paulo Henrique Rodrigues Pinheiro <paulohrpinheiro@gmail.com>"]
[dependencies]
libc = "0.2.8"
use std::io;
use std::io::prelude::*;
use std::ffi::CString;
extern crate libc;
use libc::{c_char, hostent};
#[link(name="c")]
extern {
fn gethostbyname(name: *mut c_char) -> *mut hostent;
}
fn get_ip(hostname :&str) -> Option<Vec<String>> {
let name = CString::new(hostname).unwrap();
let to_resolv = name.as_ptr() as *mut i8;
let gethost_result :*mut hostent = unsafe { gethostbyname(to_resolv) };
if gethost_result.is_null() {
return None;
}
let mut list = unsafe { (*gethost_result ).h_addr_list };
let mut result :Vec<String> = vec![];
while unsafe { !(*list ).is_null() } {
let mut octet :*const c_char = unsafe { *list };
let mut i = 0;
let mut formatted_ip = String::new();
loop {
if 0 != i { formatted_ip = format!("{}.", formatted_ip) };
formatted_ip = format!("{}{}", formatted_ip, unsafe { (*octet as u32)&0xff });
if i<(unsafe { (*gethost_result).h_length-1 }) {
octet = unsafe { octet.offset(1) };
i += 1;
}
else {
break;
}
}
result.push(formatted_ip);
list = unsafe { list.offset(1) } ;
}
Some(result)
}
fn main() {
let stdin = io::stdin();
for l in stdin.lock().lines() {
let line = l.unwrap();
println!("{:?} => {:?}", line, get_ip(&line));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment