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() {

    for domain in domains.iter(){
        let mut domain_port = String::new();
        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:


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 ""-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

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.