Transform domain to socket address

Here is a short code which get valid domain and prints domain's IP address. How do you write a simple code to convert domain into IP? This short code get domains from input & pipe.

use std::io;
use std::io::prelude::*;
use std::net::ToSocketAddrs;
fn main(){
    let stdin = io::stdin();

    let mut domains: Vec<String> = Vec::new();
    for line in stdin.lock().lines() {
        domains.push(line.unwrap())
    }


    for domain in domains.iter(){
        let mut domain_port = String::new();
        domain_port.push_str(domain);
        domain_port.push_str(":53");
        println!("{} {:?}",domain, domain_port.to_socket_addrs().unwrap().next().unwrap()   );
    }
}

I want to get rid of 53 as port number.
Code need to pass invalid domains, what's your suggestion?

In order to map an IP to a domain (or vice-versa in this case), you need a DNS server to do that for you. This crate should provide you a straightforward solution: https://docs.rs/trust-dns-resolver/0.19.6/trust_dns_resolver/

2 Likes

Yep, as nologik suggested, you're going to use DNS to translate from domain to IP.

Looks like you'd specifically want the Resolver::lookup_ip function, which returns an iterator over IP addresses. You could probably take the first element.

That'll give you an IpAddr, not a socket address, since ports are not a part of DNS. I might suggest that, if you need to convert from a "example.domain.com:53"-type string, you manually split on the last ':' character, run the domain part through DNS to get the IP, parse the port part, then put them back together yourself to get the socket address.

1 Like