Parse "localhost:8888" for SocketAddr

When I use clap-rs with a field:

#[clap(about = "Socket address to listen")]
addr: SocketAddr,

and pass "localhost:8888" as the arg, it fails with

error: Invalid value for '<ADDR>': invalid IP address syntax

I notice that it's because SocketAddr doesn't accept "localhost" as the host. But why? How can I support parsing such endpoint string?

localhost is a domain name, not an IP address. You can utilize .to_socket_addrs() to perform some basic DNS lookup.

1 Like

Thanks! We finally use tokio's TcpListener which internally calls to_socket_addrs and resolve the domain.

https://github.com/engula/engula/pull/223

Note that Tokio has a method for resolving the domain directly. It's called tokio::net::lookup_host.

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.